【发布时间】:2014-01-17 09:54:35
【问题描述】:
所以我正在制作一个程序,该程序从服务器检索图像,该图像在 AES/ECB 中加密并使用 PKCS#5 填充。我知道用于加密图像的单个同步密钥(M02cnQ51Ji97vwT4),但是,在我用来解密它的代码中,它需要我输入一个我不知道其值的 IV。
这是我用来解密它的代码:
public static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
这是我正在调用的用于解密图像的当前代码,然后将其放到我的桌面:
Byte[] lnByte = Encoding.UTF8.GetBytes(General.DecryptStringFromBytes(reader.ReadBytes(1 * 1024 * 1024 * 10), Encoding.UTF8.GetBytes("M02cnQ51Ji97vwT4"), Encoding.UTF8.GetBytes("\0")));
using (FileStream lxFS = new FileStream("C:\\Users\\Admin\\Desktop\\image.jpg", FileMode.Create))
{
lxFS.Write(lnByte, 0, lnByte.Length);
}
此代码运行没有任何错误,但是当我打开它保存的图像时,它说它已损坏或损坏。
现在将 IV 设置为“\0”的原因是因为这是我在网上找到的,但它不起作用。
如果我必须将 IV 设置为什么,我们将不胜感激。谢谢。
【问题讨论】:
-
您不必用
rijAlg.Mode = CipherMode.ECB;指定模式(即ECB)吗?否则,它将默认使用 CBC。 -
@bgamlath 没有意识到我必须这样做,谢谢。现在我该如何处理 IV?
-
先用0 IV检查一下,如果没有,恐怕你必须以某种方式找到它..:-)
-
@bgamlath ECB 模式不使用 IV,因此您不必出示它。请注意,零 IV 应包含一个零值字节块(在这种情况下为 16,或者属性值
rijAlg.BlockSize / 8 -
请注意,一般情况下,不应使用 ECB 模式,并且密码与密钥不同。因此,即使它在底层使用了 AES,该协议也并不像应有的那样安全。
标签: c# encryption cryptography aes