有时候正确,有时候出错,用旧的方式就没有出错。
出错:Specified padding mode is not valid for this algorithm
代码如下:
if (string.IsNullOrEmpty(encryptedData)) return “”;
using (var aes = Aes.Create())
{
byte[] buffer = Convert.FromBase64String(encryptedData);
aes.BlockSize = 128;
aes.Key = Convert.FromBase64String(sessionKey);
aes.IV = Convert.FromBase64String(iv);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using (var outputStream = new MemoryStream())
{
using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
using (var inputStream = new MemoryStream(buffer))
using (var cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read))
{
cryptoStream.CopyTo(outputStream);
}
var output = outputStream.ToArray();
return Encoding.UTF8.GetString(output);
}
}