【发布时间】:2019-09-02 19:53:35
【问题描述】:
我正在使用 AES 加密,我在解密时加密和写入数据库没有问题,它返回 null。
加密时Key和IV是一样的,也检查了padding,加密和解密时是一样的。
public byte[] Encrypt(string plainText, byte[] Key, byte[] IV)
{
byte[] password;
// Create a new AesManaged.
using (AesManaged aes = new AesManaged())
{
// Create encryptor
ICryptoTransform encryptor = aes.CreateEncryptor(Key, IV);
// Create MemoryStream
using (MemoryStream ms = new MemoryStream())
{
// Create crypto stream using the CryptoStream class. This class is the key to encryption
// and encrypts and decrypts data from any given stream. In this case, we will pass a memory stream
// to encrypt
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
// Create StreamWriter and write data to a stream
using (StreamWriter sw = new StreamWriter(cs))
sw.Write(plainText);
password = ms.ToArray();
}
}
}
}
public static string Decrypt(byte[] cipherText, byte[] Key, byte[] IV)
{
string plaintext = null;
// Create AesManaged
using (AesManaged aes = new AesManaged())
{
// Create a decryptor
ICryptoTransform decryptor = aes.CreateDecryptor(Key, IV);
// Create the streams used for decryption.
using (MemoryStream ms = new MemoryStream(cipherText))
{
// Create crypto stream
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
// Read crypto stream
using (StreamReader reader = new StreamReader(cs))
plaintext = reader.ReadToEnd(); // Error is here , Throws exception "Padding is invalid and cannot be removed."
}
}
}
return plaintext;
}
Result : Decryption is achieved as expected
【问题讨论】:
-
如何生成
Key和IV来调用这些方法? -
目前在代码中同时拥有用于加密/解密硬编码的密钥和 IV,
-
根据代码中的注释,不是“返回null”,而是抛出异常。这些是非常不同的事情。请编辑您的问题并明确实际发生的情况。
-
谢谢,我已经更新了问题。
-
我的精神力量预测你在接收来自 Encrypt 的
byte[]输出和能够将byte[]传递给 Decrypt 之间做坏事。我的具体预测是,您在某处使用UTF8.GetString之类的东西将字节转换为字符串。
标签: c# asp.net encryption aes