我需要一些简单的字符串加密,所以我编写了以下代码(来自 here的大量“灵感”): // create and initialize a crypto algorithm private static SymmetricAlgorithm getAlgorithm(string password) { SymmetricAlgorithm alg
// create and initialize a crypto algorithm
private static SymmetricAlgorithm getAlgorithm(string password) {
SymmetricAlgorithm algorithm = Rijndael.Create();
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(
password, new byte[] {
0x53,0x6f,0x64,0x69,0x75,0x6d,0x20, // salty goodness
0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65
}
);
algorithm.Padding = PaddingMode.ISO10126;
algorithm.Key = rdb.GetBytes(32);
algorithm.IV = rdb.GetBytes(16);
return algorithm;
}
/*
* encryptString
* provides simple encryption of a string, with a given password
*/
public static string encryptString(string clearText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
/*
* decryptString
* provides simple decryption of a string, with a given password
*/
public static string decryptString(string cipherText, string password) {
SymmetricAlgorithm algorithm = getAlgorithm(password);
byte[] cipherBytes = Convert.FromBase64String(cipherText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
return System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
代码似乎工作正常,除了在用不正确的密钥解密数据时,我在decryptString中的cs.Close()行上得到CryptographicException – “Padding无效且无法删除”.
示例代码:
string password1 = "password";
string password2 = "letmein";
string startClearText = "The quick brown fox jumps over the lazy dog";
string cipherText = encryptString(startClearText, password1);
string endClearText = decryptString(cipherText, password2); // exception thrown
我的问题是,这是预期的吗?我原本以为用错误的密码解密只会导致无意义的输出,而不是异常.
虽然这已经得到了回答,但我认为解释为什么会出现这种情况是个好主意.通常应用填充方案,因为大多数加密过滤器在语义上不安全并且防止某些形式的加密包.例如,通常在RSA中使用OAEP填充方案来防止某些类型的攻击(例如选择的明文攻击或blinding).
填充方案在发送消息之前将一些(通常)随机垃圾附加到消息m.例如,在OAEP方法中,使用了两个Oracles(这是一个简单的解释):
>给定模数的大小,用0和k0位随机数填充k1位.
>然后通过对消息应用一些转换,您将获得加密并发送的填充消息.
这为您提供了消息的随机化,并提供了一种测试消息是否为垃圾的方法.由于填充方案是可逆的,当您解密消息而您无法说明消息本身的完整性时,您实际上可以对填充做出一些断言,因此您可以知道消息是否已被正确解密或者你做错了什么(即有人篡改了消息或你使用了错误的密钥)
