查询各种资料,按照如下代码解密,解密结果不是指定的格式,求高手指点或解密源码
public string AES_decrypt(string encryptedDataStr, string key, string iv)
{
RijndaelManaged rijalg = new RijndaelManaged();
rijalg.BlockSize = 128;
rijalg.Padding = PaddingMode.None;
rijalg.Mode = CipherMode.CBC;
byte[] encryptedData = Convert.FromBase64String(encryptedDataStr);
byte[]keyBytes= Convert.FromBase64String(key);
rijalg.Key = keyBytes;
keyBytes = Convert.FromBase64String(iv);
byte[] IV = new byte[16];
Array.Copy(keyBytes, IV, 16);
rijalg.IV = IV;
byte[] msg = new byte[encryptedData.Length + 32 - encryptedData.Length % 32];
Array.Copy(encryptedData, msg, encryptedData.Length);
byte[] pad = KCS7Encoder(encryptedData.Length);
Array.Copy(pad, 0, msg, encryptedData.Length, pad.Length);
//解密
ICryptoTransform decryptor = rijalg.CreateDecryptor(rijalg.Key, rijalg.IV);
string result;
byte[] rrs = decryptor.TransformFinalBlock(msg, 0, msg.Length);
result = Convert.ToBase64String(rrs);
return result;
}
private static byte[] KCS7Encoder(int text_length)
{
int block_size =32;
// 计算需要填充的位数
int amount_to_pad = block_size - (text_length % block_size);
if (amount_to_pad == 0)
{
amount_to_pad = block_size;
}
// 获得补位所用的字符
char pad_chr = chr(amount_to_pad);
string tmp = "";
for (int index = 0; index < amount_to_pad; index++)
{
tmp += pad_chr;
}
return Encoding.UTF8.GetBytes(tmp);
}
static char chr(int a)
{
byte target = (byte)(a & 0xFF);
return (char)target;
}
找到这个解密方式。你试下。
public string AES_decrypt(string encryptedDataStr, string key, string iv)
{
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;
}