我一直收到System.Security.Cryptography.CryptographicException:“填充无效,无法删除。”尽管在许多其他堆栈溢出页面中连续搜索了数小时,但我仍然无法使它正常工作。
public static byte[] encrypt(String someString)
{
byte[] encrypted;
using (AesManaged theAes = new AesManaged())
{
theAes.Key = stringToByteArray("dd0ecb45c37b2fa02f7d924de0e48301"); //You may replace this key with any AES 128-bit key
byte[] IV = new byte[] { 126, 182, 142, 1, 77, 79, 233, 113, 245, 119, 111, 19, 124, 160, 120, 17 }; //You may replace this with your own IV
theAes.IV = IV;
var encryptor = theAes.CreateEncryptor(theAes.Key, theAes.IV);
using (var mem = new MemoryStream())
{
using (var crypto = new CryptoStream(mem, encryptor, CryptoStreamMode.Write))
{
using (var sWriter = new StreamWriter(crypto))
{
sWriter.Write(someString);
crypto.FlushFinalBlock();
}
encrypted = mem.ToArray();
}
}
}
return encrypted;
}
public static byte[] stringToByteArray(String hex)
{
int hexLength = hex.Length;
byte[] bytes = new byte[hexLength / 2];
for (int i = 0; i < hexLength; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
public static string decrypt(byte[] cipherText)
{
string decrypted;
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.Key = stringToByteArray("[Insert Key in string form here]"); //You may replace this key with any AES 128-bit key
byte[] IV = new byte[] { [Insert something here] }; //You may replace this with your own IV
aesAlg.IV = IV;
var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (var msDecrypt = new MemoryStream(cipherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
decrypted = srDecrypt.ReadToEnd();
}
}
}
}
return decrypted;
}
这就是我用于客户端服务器应用程序的加密tcp连接的方式。请帮忙!我不想使用ssl,所以请不要告诉我。
更新:所以有人说这是重复的,但事实并非如此。我尝试返回基数为64的字符串而不是字节数组,但在同一行代码中仍遇到相同的错误,即“ decrypted = srDecrypt.ReadToEnd();”