gpt4 book ai didi

c# - 加密和解密 MemoryStream

转载 作者:太空宇宙 更新时间:2023-11-03 23:07:36 24 4
gpt4 key购买 nike

我需要加密并稍后解密 MemoryStream(原始大型 PDF 文件)。我尝试了以下代码:

    public static string GenerateKey()
{
var desCrypto = (DESCryptoServiceProvider)DES.Create();

return Encoding.ASCII.GetString(desCrypto.Key);
}

public static MemoryStream Encrypt(Stream fsInput,string sKey)
{
var fsEncrypted=new MemoryStream();

var des = new DESCryptoServiceProvider
{
Key = Encoding.ASCII.GetBytes(sKey),
IV = Encoding.ASCII.GetBytes(sKey)
};
var desencrypt = des.CreateEncryptor();
var cryptostream = new CryptoStream(fsEncrypted,desencrypt,CryptoStreamMode.Write);

var bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
fsInput.Close();

fsEncrypted.Flush();
fsEncrypted.Position = 0;
return fsEncrypted;
}

public static MemoryStream Decrypt(Stream fsread,string sKey)
{
var des = new DESCryptoServiceProvider
{
Key = Encoding.ASCII.GetBytes(sKey),
IV = Encoding.ASCII.GetBytes(sKey)
};

var sOutputFilename = new MemoryStream();
var desdecrypt = des.CreateDecryptor();
var cryptostreamDecr = new CryptoStream(fsread,desdecrypt,CryptoStreamMode.Read);

var fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
sOutputFilename.Position = 0;

return sOutputFilename;
}

调用示例:

    var sSecretKey = FileHelper.GenerateKey();
var encyptedPdfContent = FileHelper.Encrypt(httpPostedFile.InputStream, sSecretKey);

var decryptedPdfContent = FileHelper.Decrypt(encyptedPdfContent, sSecretKey);

加密似乎按预期工作,但当我尝试解密时

fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());

返回给我 Bad Data 异常。

我的代码有什么问题?

我看了其他帖子,都是跟字符串编码(Encoding.Unicode)有关的。我没有字符串。我有一个根本没有编码的内存流!

最佳答案

请在解密方法中加入以下代码

des.Padding = PaddingMode.Zeros;

关于c# - 加密和解密 MemoryStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40650872/

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