2016-11-17 21 views
1

我需要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)有關。我沒有字符串。我有一個完全沒有編碼的記憶流!

+0

[「Bad Data」CryptographicException]的可能重複(http://stackoverflow.com/questions/9659898/bad-data-cryptographicexception) – TheLethalCoder

+0

我看到這篇文章,它涉及到字符串編碼(Encoding.Unicode) 。我沒有字符串。我有一個完全沒有編碼的記憶流! – danyolgiax

+0

我知道,但我只是假設你會讀取所有的內容,然後傳遞一個字符串,而不是流 – TheLethalCoder

回答

1

請在解密方法中添加以下代碼

des.Padding = PaddingMode.Zeros; 
+0

這個固定的'Bad Data'錯誤!謝謝! – danyolgiax

1

您需要調用Write可以做到這一點後刷新cryptoStream使用FluchFinalBlock

cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length); 
cryptostream.FlushFinalBlock(); 

而且在你Decrypt方法你通過關閉StreamWriter來處理退貨流,因此只需刪除此行:

fsDecrypted.Close(); 
+0

加入'PaddingMode.Zeros'的錯誤已修復,但你的答案也是有用的!謝謝 – danyolgiax

+0

@danyolgiax沒問題我對上面的代碼進行了修改,它也起作用,可能值得使用它們,只是爲了確保 – TheLethalCoder