我在项目中使用了System.Security.Cryptography.Aes进行了加密和解密。当我在解密时,我输入正确的密钥时,一切正常,被加密的内容会被解密成原本正确的内容。但是当我故意输入错误的密钥时,我以为被加密的内容会被解密成错误的内容,结果却不是如此,而是发生了报错,请问这正常吗?
下面是我从密码框中得到KEY和IV的代码:
public static void GenKeyIV(string password, out byte[] key, out byte[] iv)
{
using (Aes aes = Aes.Create())
{
key = new byte[aes.Key.Length];
byte[] pwdBytes = Encoding.UTF8.GetBytes(password);
for (int i = 0; i < pwdBytes.Length; i++)
{
key[i] = pwdBytes[i];
}
iv = new byte[aes.IV.Length];
for (int i = 0; i < pwdBytes.Length; i++)
{
iv[i] = pwdBytes[i];
}
}
}
下面是我解密的代码:
public static void DescrptString(string filepath, string savepath, byte[] key, byte[] iv)
{
StreamReader sr = new StreamReader(filepath);
byte[] encontent = Convert.FromBase64String(sr.ReadToEnd());
sr.Close();
byte[] decontent;
using (Aes aesAlg = Aes.Create())
{
ICryptoTransform decryptor = aesAlg.CreateDecryptor(key, iv);
MemoryStream ms2 = new MemoryStream(encontent);
CryptoStream cs = new CryptoStream(ms2, decryptor, CryptoStreamMode.Read);
using (MemoryStream ms3 = new MemoryStream())
{
cs.CopyTo(ms3);
decontent = ms3.ToArray();
}
cs.Close();
ms2.Close();
}
FileStream ff = new FileStream(savepath, FileMode.Create, FileAccess.Write);
ff.Write(decontent, 0, decontent.Length);
ff.Close();
}
然后报错位置就是下图断点处语句