爲了解決這個問題,通常IV是針對每個超文本隨機生成的,並且預先不加密到加密數據。通過這種方式,每個加密數據都與其他數據不同。
在代碼應該是
string str = "abcdefghijklmno|axXXyyYY343433553353afsafaadfafdfsafsf|2013-01-01T00:00:00";
byte[] data = Encoding.UTF8.GetBytes(str);
byte[] key = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; // Your random key, I hope more random!
byte[] encrypted;
// Encrypt
using (var am = new AesManaged())
using (var rng = new RNGCryptoServiceProvider())
{
am.Key = key;
var iv = new byte[am.BlockSize/8];
rng.GetBytes(iv);
am.IV = iv;
using (var encryptor = am.CreateEncryptor())
using (var ms = new MemoryStream())
{
ms.Write(iv, 0, iv.Length);
using (var encStream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
encStream.Write(data, 0, data.Length);
}
encrypted = ms.ToArray();
}
}
// Decrypt
string str2;
using (var am = new AesManaged())
using (var ms = new MemoryStream(encrypted))
{
am.Key = key;
var iv = new byte[am.BlockSize/8];
ms.Read(iv, 0, iv.Length);
am.IV = iv;
using (var decryptor = am.CreateDecryptor())
using (var decStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (var ms2 = new MemoryStream())
{
decStream.CopyTo(ms2);
str2 = Encoding.UTF8.GetString(ms2.GetBuffer(), 0, (int)ms2.Length);
}
}
注意,在一般IV重用導致加密的弱點。參見例如wiki:
對於CBC和CFB,重用IV泄露關於明文的第一個塊的某些信息,和關於由兩個消息共享的任何公共前綴。對於OFB和CTR,重複使用IV完全破壞了安全性。[6]
請顯示您用於生成密鑰/ IV的代碼。 – Iridium
@Iridium Key/IV是通過使用AesManaged類並調用GenerateIV和GenerateKey方法生成的,但它們都是固定的。下面的答案表明我應該爲每條消息更改IV。 – Andy