贴上代码,AES-CBC- PKCS7加密解密, 之前可以的,不知道什么时候就不行了,报错( padding is invalid and cannot be removed.),不知道哪里有bug,各位大佬请看看
[C#] 纯文本查看 复制代码 public static class CryptoHelper
{
/// <summary>
/// AES 加密
/// </summary>
/// <param name="plainText">密文</param>
/// <param name="Key">加密key</param>
/// <param name="IV">初始化向量 (字节数组,16字节长度)</param>
/// <returns></returns>
public static string AesEncrypt(string plainText, byte[] Key, byte[] IV)
{
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.KeySize = 256;
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.BlockSize = 128;
using (ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV))
{
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
}
return ToHex(encrypted);
}
/// <summary>
/// AES 解密
/// </summary>
/// <param name="cipherText">密文(字节数组)</param>
/// <param name="key">加密key(字节数组)</param>
/// <param name="iv">初始化向量 (字节数组,16字节长度)</param>
/// <returns></returns>
public static string AesDecrypt(byte[] cipherText, byte[] key, byte[] iv)
{
string plainText = "";
using (Aes _aes = Aes.Create())
{
_aes.KeySize = 256;
_aes.Key = key;
_aes.IV = iv;
_aes.Mode = CipherMode.CBC;
_aes.Padding = PaddingMode.PKCS7;
_aes.BlockSize = 128;
using (ICryptoTransform transform = _aes.CreateDecryptor(_aes.Key, _aes.IV))
{
using (MemoryStream ms = new MemoryStream(cipherText))
{
using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
plainText = sr.ReadToEnd();
}
}
}
}
}
return plainText;
}
public static string ToHex(byte[] _bytes)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < _bytes.Length; i++)
{
sb.Append(_bytes[i].ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// 字符串转16进制字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] HexStrToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
} |