AES解密时遇到 填充无效 无法被移除
public byte[] AesEncrypt(byte[] content, byte[] aesKey)
{
var _aes = new RijndaelManaged();
_aes.Padding = PaddingMode.PKCS7;
_aes.Mode = CipherMode.CBC;
byte[] byteIV = new byte[16];
_aes.Key = aesKey;
_aes.IV = byteIV;
var _crypto = _aes.CreateEncryptor(aesKey, byteIV);
byte[] data = _crypto.TransformFinalBlock(
content, 0, content.Length);
_crypto.Dispose();
return data;
}
public byte[] AesDecrypt(byte[] content, byte[] aesKey)
{
var _aes = new RijndaelManaged();
_aes.Padding = PaddingMode.PKCS7;
_aes.Mode = CipherMode.CBC;
byte[] byteIV = new byte[16];
_aes.Key = aesKey;
_aes.IV = byteIV;
var _crypto = _aes.CreateDecryptor();
byte[] decrypted = _crypto.TransformFinalBlock(
content, 0, content.Length);
_crypto.Dispose();
return decrypted;
}
使用以上代码先加密得到密文,再用同一key对密文解密时,总是提示填充无效 无法被移除。
后来发现是PaddingMode设置问题
因为加密返回的字节数超长,业务处理的地方一直限制64字节,所以导致该异常。
蒋PaddingMode设为PaddingMode.Zeros后问题解决。
同样取消业务处理中的64位限制,同样正常解密。
PaddingMode的解释
ZeroPadding,数据长度不对齐时使用0填充,否则不填充。
PKCS7Padding,假设数据长度需要填充n(n>0)个字节才对齐,那么填充n个字节,每个字节都是n;如果数据本身就已经对齐了,则填充一块长度为块大小的数据,每个字节都是块大小。
PKCS5Padding,PKCS7Padding的子集,块大小固定为8字节。