c# AES加解密问题
贴上代码,AES-CBC- PKCS7加密解密, 之前可以的,不知道什么时候就不行了,报错( padding is invalid and cannot be removed.),不知道哪里有bug,各位大佬请看看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.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;
for (int i = 0; i < returnBytes.Length; i++)
returnBytes = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
} 移除BlockSize这一行就行了 icysky0605 发表于 2022-3-21 16:42
移除BlockSize这一行就行了
这是为什么那,不能设置,我原来就行啊{:301_971:} WolfAvenue 发表于 2022-3-21 17:00
这是为什么那,不能设置,我原来就行啊
我也不清楚,因为我没深入研究过,我以前的代码都没有这一行的 这个aes加密出来的字符串是可破解的吧,弱弱的问一句大佬,怎样写死码加密的字符串啊 落红护花 发表于 2022-3-21 19:40
这个aes加密出来的字符串是可破解的吧,弱弱的问一句大佬,怎样写死码加密的字符串啊
万物皆可破解{:301_1004:} ,死码是什么意思?没看懂
页:
[1]