我正在尝试使用 .NET 中的 RijndaelManaged 类加密一串文本。但是,我不断收到 CryptographicException(“要解密的数据长度无效”)。这条消息并不完全有帮助,特别是因为它发生在我尝试加密数据而不是解密时。下面是代码。
public static string EncryptKMSToken(string valueToEncrypt, string encryptionKey)
{
string results = string.Empty;
using (RijndaelManaged aes = new RijndaelManaged())
{
aes.BlockSize = 128;
aes.KeySize = 128;
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
UTF8Encoding byteTransform = new UTF8Encoding();
aes.Key = byteTransform.GetBytes(encryptionKey);
ICryptoTransform encryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(encryptStream))
{
writer.Write(valueToEncrypt);
}
byte[] encryptedBytes = stream.ToArray();
results = byteTransform.GetString(encryptedBytes);
}
}
}
return results;
}
错误发生在第三个 using 语句关闭时(即 writer.Write(valueToEncrypt) 之后的行。如果我尝试将两行移到第三个 using 块内的下方,我最终得到一个空字符串(并且错误仍然发生)。我直接从这个网站(http://stackoverflow.com/questions/273452/using-aes-encryption-in-c-sharp)中提取了这段代码,但它似乎不起作用。有没有人有任何想法?