gpt4 book ai didi

c# - 如何解密使用 RijndaelManaged 加密的文件

转载 作者:行者123 更新时间:2023-11-30 18:42:24 27 4
gpt4 key购买 nike

我可以加密图像文件。但无法解密该文件。

while ((readLen = cryptStrm.Read(bs, 0, bs.Length)) > 0)

谁能猜出哪一部分是错的?我编写的代码如下。

当我读取加密文件时,我根本无法读取。并且 CryptoStream 的名为长度和位置的属性具有“NotSupportedException”,当我使用 vss 看到 cryptstream 的属性时。

我浪费了很多时间来解决这个问题.....请帮助我.....

加密[位图>>加密文件]

解密[加密文件>>文件]


加密

    public static void EncryptFile(
Bitmap bmp, string destFile, byte[] key, byte[] iv)
{

System.Security.Cryptography.RijndaelManaged rijndael =
new System.Security.Cryptography.RijndaelManaged();

rijndael.Key = key;
rijndael.IV = iv;

System.IO.FileStream outFs = new System.IO.FileStream(
destFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);

System.Security.Cryptography.ICryptoTransform encryptor =
rijndael.CreateEncryptor();

System.Security.Cryptography.CryptoStream cryptStrm =
new System.Security.Cryptography.CryptoStream(
outFs, encryptor,
System.Security.Cryptography.CryptoStreamMode.Write);

MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Jpeg);


byte[] bs = new byte[1024];
int readLen;
while ((readLen = ms.Read(bs, 0, bs.Length)) > 0)
{
cryptStrm.Write(bs, 0, readLen);
}

ms.Close();
cryptStrm.Close();
encryptor.Dispose();
outFs.Close();
}

解密

    public static void DecryptFile(
string sourceFile, string destFile, byte[] key, byte[] iv)
{

System.Security.Cryptography.RijndaelManaged rijndael =
new System.Security.Cryptography.RijndaelManaged();

rijndael.Key = key;
rijndael.IV = iv;

System.IO.FileStream inFs = new System.IO.FileStream(
sourceFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);

System.Security.Cryptography.ICryptoTransform decryptor =
rijndael.CreateDecryptor();

System.Security.Cryptography.CryptoStream cryptStrm =
new System.Security.Cryptography.CryptoStream(
inFs, decryptor,
System.Security.Cryptography.CryptoStreamMode.Read);

System.IO.FileStream outFs = new System.IO.FileStream(
destFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
byte[] bs = new byte[1024];
int readLen;

while ((readLen = cryptStrm.Read(bs, 0, bs.Length)) > 0)
{
outFs.Write(bs, 0, readLen);
}

outFs.Close();
cryptStrm.Close();
decryptor.Dispose();
inFs.Close();
}

最佳答案

尝试设置 rijndael 的 Mode 和 Padding 成员。
当我做类似的实现时,默认的填充模式导致了问题。

            // It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
rijndael.Mode = CipherMode.CBC;
rijndael.Padding = PaddingMode.None;

关于c# - 如何解密使用 RijndaelManaged 加密的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5827600/

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