直接上代码:
/// <summary>
/// 微信小程序 encryptedData 解密
/// </summary>
/// <param name="encryptedDataStr"></param>
/// <param name="key">session_key</param>
/// <param name="iv">iv</param>
/// <returns></returns>
public string AES_decrypt22(string encryptedDataStr, string key, string iv)
{
var rijalg = Aes.Create();
// RijndaelManaged rijalg = new RijndaelManaged();
//-----------------
//设置 cipher 格式 AES-128-CBC
rijalg.KeySize = 128;
rijalg.Padding = PaddingMode.PKCS7;
rijalg.Mode = CipherMode.CBC;
rijalg.Key = Convert.FromBase64String(key);
rijalg.IV = Convert.FromBase64String(iv);
byte[] encryptedData = Convert.FromBase64String(encryptedDataStr);
//解密
ICryptoTransform decryptor = rijalg.CreateDecryptor(rijalg.Key, rijalg.IV);
string result;
using (MemoryStream msDecrypt = new MemoryStream(encryptedData))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
result = srDecrypt.ReadToEnd();
}
}
}
return result;
}