我在使用 RijndaelManaged 时遇到了一个奇怪的问题。基本上我有一个新的实例,我在其中设置了 CipherMode、Padding、IV 和 Key。然后我创建另一个实例并将原始实例的以下属性的相同值分配给第二个实例:Mode、Padding、KeySize、FeedbackSize、BlockSize、IV 和 Key。
因此,将所有属性值从实例 1 复制到实例 2 后,我应该得到相同的结果,对吧?错误的!两个实例的 GetHashCode() 以某种方式不同,但如果我转储它们的属性(如上所述),那么它们都是相同的。
如果我加密长度等于块大小(16 字节,128 位)的文本字符串,那么两者都会产生相同的结果,如果输入小于 BlockSize,则加密结果不一样。
我有这个来创建初始 Rijndael 实例。
public static RijndaelManaged CreateSymmetricKey(string passphrase)
{
RijndaelManaged symCrypto = new RijndaelManaged();
symCrypto.Mode = CipherMode.CBC;
symCrypto.Padding = PaddingMode.PKCS7;
byte[] salt = Encoding.UTF8.GetBytes("dummy dummy dummy dummy test");
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(passphrase, salt);
symCrypto.Key = key.GetBytes(symCrypto.KeySize / 8);
symCrypto.IV = key.GetBytes(symCrypto.BlockSize / 8);
return symCrypto;
}
为了举例说明对字符串进行加密:
private string Encrypt(RijndaelManaged rm, string text)
{
byte[] encrypted;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rm.CreateEncryptor(rm.Key, rm.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(text);
}
encrypted = msEncrypt.ToArray();
}
}
return BitConverter.ToString(encrypted);
}
那么就这样做
RijndaelManaged rm1 = CreateSymmetricKey("there is something weird happening");
RijndaelManaged rm2 = new RijndaelManaged();
// copy ALL public properties to the new instance so that it has the same parameters
rm2.BlockSize = rm1.BlockSize; // 128
rm2.FeedbackSize = rm1.FeedbackSize; // 128
rm2.KeySize = rm1.KeySize; // 256
rm2.Mode = rm1.Mode; // CBC
rm2.Padding = rm1.Padding; // PKCS7
rm2.IV = rm1.IV;
rm2.Key = rm1.Key;
// Encryption
string cypher1 = Encrypt(rm1, "this is a test 6"); // length equal to BlockSize
string cypher2 = Encrypt(rm2, "this is a test 6"); // length equal to BlockSize
string cypher11 = Encrypt(rm1, "this is a test"); // length less than BlockSize
string cypher21 = Encrypt(rm2, "this is a test"); // length less than BlockSize
我得到了 cyper1 == cypher2 和 cypher11 != cypher21 还有 rm1.GetHashCode() != rm2.GetHashCode() 但所有公共参数都是一样的!
我还转储了两个实例的所有公共属性,看看我是否遗漏了一些东西,但不是,所有值都是相同的。