gpt4 book ai didi

c# - "Padding is invalid and cannot be removed"使用 AesManaged

转载 作者:IT王子 更新时间:2023-10-29 04:12:01 25 4
gpt4 key购买 nike

我正在尝试使用 AesManaged 进行简单的加密/解密,但在尝试关闭解密流时我总是遇到异常。此处的字符串被正确加密和解​​密,然后在 Console.WriteLine 打印出正确的字符串后我得到 CryptographicException“填充无效且无法删除”。

有什么想法吗?

MemoryStream ms = new MemoryStream();
byte[] rawPlaintext = Encoding.Unicode.GetBytes("This is annoying!");

using (Aes aes = new AesManaged())
{
aes.Padding = PaddingMode.PKCS7;
aes.Key = new byte[128/8];
aes.IV = new byte[128/8];

using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(),
CryptoStreamMode.Write))
{
cs.Write(rawPlaintext, 0, rawPlaintext.Length);
cs.FlushFinalBlock();
}

ms = new MemoryStream(ms.GetBuffer());
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(),
CryptoStreamMode.Read))
{
byte[] rawData = new byte[rawPlaintext.Length];
int len = cs.Read(rawData, 0, rawPlaintext.Length);
string s = Encoding.Unicode.GetString(rawData);
Console.WriteLine(s);
}
}

最佳答案

诀窍是使用 MemoryStream.ToArray()。我还更改了您的代码,以便它在加密和解密时都使用 CryptoStream 进行写入。而且您不需要显式调用 CryptoStream.FlushFinalBlock(),因为您在 using() 语句中拥有它,并且刷新将在 Dispose 上发生()。以下对我有用。

byte[] rawPlaintext = System.Text.Encoding.Unicode.GetBytes("This is all clear now!");

using (Aes aes = new AesManaged())
{
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 128; // in bits
aes.Key = new byte[128/8]; // 16 bytes for 128 bit encryption
aes.IV = new byte[128/8]; // AES needs a 16-byte IV
// Should set Key and IV here. Good approach: derive them from
// a password via Cryptography.Rfc2898DeriveBytes
byte[] cipherText= null;
byte[] plainText= null;

using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(rawPlaintext, 0, rawPlaintext.Length);
}

cipherText= ms.ToArray();
}


using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherText, 0, cipherText.Length);
}

plainText = ms.ToArray();
}
string s = System.Text.Encoding.Unicode.GetString(plainText);
Console.WriteLine(s);
}

另外,我猜你知道你会想要显式设置 Mode的 AesManaged 实例,并使用 System.Security.Cryptography.Rfc2898DeriveBytes从密码和盐派生 key 和 IV。

另见:
- AesManaged

关于c# - "Padding is invalid and cannot be removed"使用 AesManaged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/604210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com