【发布时间】:2014-04-21 16:19:26
【问题描述】:
我在解密示例应用程序中的简单值时遇到问题。该值是使用相同的示例应用程序加密的。我已经列出了下面的代码。
当代码块完成时,结果是plain 是一个空字符串。不会引发异常。
string plain = null;
using (AesManaged alg = new AesManaged())
{
// Extract the initialization vector from the entire ciphertext
byte[] IV = new byte[alg.IV.Length];
Buffer.BlockCopy(cipherText, 0, IV, 0, alg.IV.Length);
alg.IV = IV;
alg.Key = GetKey();
ICryptoTransform transform = alg.CreateDecryptor();
// Extract the encrypted value from the entire ciphertext
byte[] encrypted = new byte[cipherText.Length - alg.IV.Length];
Buffer.BlockCopy(cipherText, alg.IV.Length, encrypted, 0, cipherText.Length - alg.IV.Length);
using (MemoryStream ms = new MemoryStream(encrypted))
{
using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Read))
{
using (StreamReader r = new StreamReader(cs))
{
cs.Flush();
plain = r.ReadToEnd();
}
}
}
}
我已验证cipherText(作为参数传递的 32 字节字节 [])具有与加密产生的值相同的字节。 IV 和 Key 也是逐字节相同的。注意:IV 由加密逻辑添加到加密值之前。这就是第一行从代码块中提取它的原因。
我还验证了encrypted byte[] 的内容与加密例程中的内容相同。内容只有 16 个字节。
我已经验证了MemoryStreamms中的Position是0,经过例程后是16。所以看起来MemoryStream被读取了。我的怀疑是我错误地使用了StreamReader,但我看不出我在哪里犯了错误。
我尝试修改加密字节[] 中的一个字节,然后如预期的那样得到CryptographicException(填充无效)。因此,从密码学的角度来看,我的 IV、密钥和加密值似乎都是有序的。出于某种原因,它可能没有一直得到处理?
感谢您的任何见解。
为完整起见,加密例程如下: byte[] 加密 = null;
using (AesManaged alg = new AesManaged())
{
System.Diagnostics.Debug.WriteLine("Key size: {0}", alg.KeySize);
alg.GenerateIV();
alg.Key = GetKey();
ICryptoTransform transform = alg.CreateEncryptor(alg.Key, alg.IV);
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
using (StreamWriter w = new StreamWriter(cs))
{
w.Write(plainText);
cs.FlushFinalBlock();
// Create a byte array big enough to hold the IV and the encrypted value
encrypted = new byte[alg.IV.Length + ms.Length];
// Copy the random generated initialization vector to the start of the encrypted bytes
Buffer.BlockCopy(alg.IV, 0, encrypted, 0, alg.IV.Length);
// Copy the encrypted value at the end
Buffer.BlockCopy(ms.ToArray(), 0, encrypted, alg.IV.Length, (int)ms.Length);
}
}
【问题讨论】:
标签: .net encryption aes