[英]Invalid padding error when using AesCryptoServiceProvider in C#
I've written a simple encryp/decrypt method in c# which uses the AES alg. 我在c#中使用AES alg编写了一个简单的encryp / decrypt方法。 When I try to encrypt and then decrypt a string with certain lengths like 4 or 7 characters, it works fine, with other lengths however It says that the padding is invalid and cannot be removed. 当我尝试加密然后解密某些长度(例如4或7个字符)的字符串时,它可以与其他长度一起正常工作,但是它表示填充无效并且无法删除。
public static string Decrypt(string text)
{
Aes a = System.Security.Cryptography.AesCryptoServiceProvider.Create();
a.Padding = PaddingMode.PKCS7;
a.Key = Convert.FromBase64String("UDlArN63HCk15fHBski/zvaWiMZJi+jR1BADvVgenCU=");
a.IV = Convert.FromBase64String("xZG/eLY8eq0mQhUXvKbUDQ==");
var dc = a.CreateDecryptor();
byte[] encryptedBytes = Encoding.Unicode.GetBytes(text);
byte[] decryptedBytes = dc.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
return Encoding.Unicode.GetString(decryptedBytes);
}
public static string Encrypt(string text)
{
Aes a = System.Security.Cryptography.AesCryptoServiceProvider.Create();
a.Padding = PaddingMode.PKCS7;
a.Key = Convert.FromBase64String("UDlArN63HCk15fHBski/zvaWiMZJi+jR1BADvVgenCU=");
a.IV = Convert.FromBase64String("xZG/eLY8eq0mQhUXvKbUDQ==");
var dc = a.CreateEncryptor();
byte[] decryptedBytes = Encoding.Unicode.GetBytes(text);
byte[] encryptedBytes = dc.TransformFinalBlock(decryptedBytes, 0, decryptedBytes.Length);
return Encoding.Unicode.GetString(encryptedBytes);
}
Ciphertexts are binary data which might contain bytes that are not printable. 密文是二进制数据,可能包含不可打印的字节。 If try to encode the byte array as a Unicode string, you will lose some bytes. 如果尝试将字节数组编码为Unicode字符串,则会丢失一些字节。 It will be impossible to recover them during decryption. 在解密过程中将无法恢复它们。
If you actually want to handle the ciphertext as a string, you need to convert it into a textual representation like Base 64 or Hex. 如果您实际上想将密文作为字符串来处理,则需要将其转换为文本表示形式,例如Base 64或Hex。
// encryption
return Convert.ToBase64String(decryptedBytes);
// decryption
byte[] decryptedBytes = Convert.FromBase64String(text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.