【发布时间】:2015-02-20 16:34:25
【问题描述】:
下面和 Fiddle 中的代码不是用于生产,而是用于教育目的。我不想解决任何问题,因为我有一个可行的解决方案。但是,我想知道为什么:
var password = "password";
var salt = Encoding.ASCII.GetBytes(password.Length.ToString());
var secret = new PasswordDeriveBytes(password, salt);
当上述实现时,在下面的方法FixedEncryptor 将起作用。
// Valid:
public static string FixedEncryptor(string content)
{
var cipher = new RijndaelManaged();
var plain = Encoding.Unicode.GetBytes(content);
var key = new PasswordDeriveBytes(password, salt);
using (var encrypt = cipher.CreateEncryptor(key.GetBytes(32), key.GetBytes(16)))
using (var stream = new MemoryStream())
using (var crypto = new CryptoStream(stream, encrypt, CryptoStreamMode.Write))
{
crypto.Write(plain, 0, plain.Length);
crypto.FlushFinalBlock();
return Convert.ToBase64String(stream.ToArray());
}
}
但是,如果你实现:
var secret = new PasswordDeriveBytes("password",
Encoding.ASCII.GetBytes("password"));
代码会突然产生:
运行时异常(第 70 行):填充无效且不能 删除。
堆栈跟踪:
[System.Security.Cryptography.CryptographicException:填充是 无效且无法删除。] 在 Crypt.Decryptor(字符串内容): Program.Main() 的第 70 行:第 17 行
如以下方法所示:
// Invalid:
public static string Encryptor(string content)
{
var cipher = new RijndaelManaged();
var plain = Encoding.Unicode.GetBytes(content);
var key = new PasswordDeriveBytes("password", Encoding.ASCII.GetBytes("password"));
using (var encrypt = cipher.CreateEncryptor(key.GetBytes(32), key.GetBytes(16)))
using (var stream = new MemoryStream())
using (var crypto = new CryptoStream(stream, encrypt, CryptoStreamMode.Write))
{
crypto.Write(plain, 0, plain.Length);
crypto.FlushFinalBlock();
return Convert.ToBase64String(stream.ToArray());
}
}
那么为什么一个可以成功解密,而另一个不能正确解密并产生上述错误?
一个小例子的小提琴是here。
【问题讨论】:
-
两段代码不等价——第一段缺少
ToString()调用。 -
@Greg 创建一个最小的fiddle 重新创建问题并在此处发布。您目前的问题不太可能得到帮助。
-
@ScottChamberlain 我做到了。
标签: c# asp.net cryptography