在做小程序时,官方没有C#的解密,自己给写一个封装,希望可以帮到大家
#region 解密
#region 私有方法
private static byte[] AES_Decrypt(String Input, byte[] Iv, byte[] Key)
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 128;//原始:256
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = Key;
aes.IV = Iv;
var decrypt = aes.CreateDecryptor(aes.Key, aes.IV);
byte[] xBuff = null;
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
{
// cs.Read(decryptBytes, 0, decryptBytes.Length);
// cs.Close();
// ms.Close();
byte[] xXml = Convert.FromBase64String(Input);
byte[] msg = new byte[xXml.Length + 32 - xXml.Length % 32];
Array.Copy(xXml, msg, xXml.Length);
cs.Write(xXml, 0, xXml.Length);
}
xBuff = decode2(ms.ToArray());
}
return xBuff;
}
private static byte[] decode2(byte[] decrypted)
{
int pad = (int)decrypted[decrypted.Length - 1];
if (pad < 1 || pad > 32)
{
pad = 0;
}
byte[] res = new byte[decrypted.Length - pad];
Array.Copy(decrypted, 0, res, 0, decrypted.Length - pad);
return res;
}
#endregion
/// <summary>
/// 解密所有消息的基础方法
/// </summary>
/// <param name="sessionKey">储存在 SessionBag 中的当前用户 会话 SessionKey</param>
/// <param name="encryptedData">接口返回数据中的 encryptedData 参数</param>
/// <param name="iv">接口返回数据中的 iv 参数,对称解密算法初始向量</param>
/// <returns></returns>
public static string DecodeEncryptedData(string sessionKey, string encryptedData, string iv)
{
var aesCipher = Convert.FromBase64String(encryptedData);
var aesKey = Convert.FromBase64String(sessionKey);
var aesIV = Convert.FromBase64String(iv);
var result = AES_Decrypt(encryptedData, aesIV, aesKey);
var resultStr = Encoding.UTF8.GetString(result);
return resultStr;
}
#endregion