我有下面的代码可用于128位十六进制密钥。但是,当我提供256位十六进制密钥(或更高版本)时,它将引发错误
消息:System.ArgumentException:指定的密钥不是有效大小 对于此算法。参数名称:rgbKey
public static string Encrypt(string text, string keyString)
{
var key = Encoding.UTF8.GetBytes(keyString);
using (var aesAlg = Aes.Create())
{
using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
{
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(text);
}
var iv = aesAlg.IV;
var decryptedContent = msEncrypt.ToArray();
var result = new byte[iv.Length + decryptedContent.Length];
Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);
return Convert.ToBase64String(result);
}
}
}
}
如何使用具有256位或更高密钥的AES?
答案 0 :(得分:-1)
尝试将填充模式设置为PKCS7。
aesAlg.Padding = PaddingMode.PKCS7。