gpt4 book ai didi

c# - 使用未知 IV 解密 PKCS#5 填充的 AES/ECB

转载 作者:太空宇宙 更新时间:2023-11-03 10:51:47 25 4
gpt4 key购买 nike

所以我正在制作一个程序,从服务器中检索图像,该图像在 AES/ECB 中加密并使用 PKCS#5 填充。我知道用于加密图像的单个同步 key (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 设置为什么的任何帮助,我们将不胜感激。谢谢。

最佳答案

ECB 模式不需要 IV。但如果我没记错的话,RijndaelManaged 默认为 CBC。因此,您使用的解密模式与加密模式不同。最好不要对 key 大小、加密模式或填充模式等使用默认值。

明确将加密模式设置为 ECB 并将填充模式设置为 PKCS#7 填充后重试。您不必为 ECB 提供 IV。

如果您确实必须为实现提供它,请提供全零的 IV。在 CBC 模式下,IV 与第一 block 明文进行异或运算,因此很容易看出全零的 IV 作用不大。

如果您使用零 IV 的 CBC 而不是 ECB,那么前 16 个字节(一个 block )将是正确的。之后的所有 block 都是随机的。大多数时候你会在最后收到一个填充错误,但你可能是“幸运的”(大约每 256 次)并在最后得到一个正确的填充。


此外,您将图像转换为字符编码(字符串)并返回。这在大多数情况下会导致数据丢失。相反,您应该将图像视为二进制图像。

public static void DecryptStringFromBytes(byte[] cipherText, byte[] Key, Stream stream)
{
// ...

// Don't use StreamReader

csDecrypt.CopyTo(stream)

// ...
}

现在将您生成的 FileStream 作为最后一个参数提供给该方法。

关于c# - 使用未知 IV 解密 PKCS#5 填充的 AES/ECB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21182815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com