我需要加密并稍后解密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)有关。我没有字符串。我有一个根本没有编码的内存流!
答案 0 :(得分:2)
请在解密方法
中添加以下代码des.Padding = PaddingMode.Zeros;
答案 1 :(得分:1)
您需要在致电cryptoStream
之后刷新Write
这可以使用FluchFinalBlock
来完成:
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.FlushFinalBlock();
同样在您的Decrypt
方法中,您通过关闭StreamWriter
来处理退货流,所以只需删除此行:
fsDecrypted.Close();