我需要crypt並稍後解密MemoryStream(原始大型PDF文件)。我嘗試下面的代碼:加密和解密一個MemoryStream
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)有關。我沒有字符串。我有一個完全沒有編碼的記憶流!
[「Bad Data」CryptographicException]的可能重複(http://stackoverflow.com/questions/9659898/bad-data-cryptographicexception) – TheLethalCoder
我看到這篇文章,它涉及到字符串編碼(Encoding.Unicode) 。我沒有字符串。我有一個完全沒有編碼的記憶流! – danyolgiax
我知道,但我只是假設你會讀取所有的內容,然後傳遞一個字符串,而不是流 – TheLethalCoder