2014-12-01 101 views
1

我要壓縮,並通過使用這個簡單的代碼進行加密一氣呵成文件:DeflateStream/GZipStream到CryptoStream的,反之亦然

public void compress(FileInfo fi, Byte[] pKey, Byte[] pIV) 
{ 
    // Get the stream of the source file. 
    using (FileStream inFile = fi.OpenRead()) 
    {     
     // Create the compressed encrypted file. 
     using (FileStream outFile = File.Create(fi.FullName + ".pebf")) 
     { 
      using (CryptoStream encrypt = new CryptoStream(outFile, Rijndael.Create().CreateEncryptor(pKey, pIV), CryptoStreamMode.Write)) 
      { 
       using (DeflateStream cmprss = new DeflateStream(encrypt, CompressionLevel.Optimal)) 
       { 
        // Copy the source file into the compression stream. 
        inFile.CopyTo(cmprss); 
        Console.WriteLine("Compressed {0} from {1} to {2} bytes.", fi.Name, fi.Length.ToString(), outFile.Length.ToString()); 
       } 
      } 
     } 
    } 
} 

以下線將恢復加密文件和壓縮文件恢復到原來的:

public void decompress(FileInfo fi, Byte[] pKey, Byte[] pIV) 
{ 
    // Get the stream of the source file. 
    using (FileStream inFile = fi.OpenRead()) 
    { 
     // Get original file extension, for example "doc" from report.doc.gz. 
     String curFile = fi.FullName; 
     String origName = curFile.Remove(curFile.Length - fi.Extension.Length); 

     // Create the decompressed file. 
     using (FileStream outFile = File.Create(origName)) 
     { 
      using (CryptoStream decrypt = new CryptoStream(inFile, Rijndael.Create().CreateDecryptor(pKey, pIV), CryptoStreamMode.Read)) 
      { 
       using (DeflateStream dcmprss = new DeflateStream(decrypt, CompressionMode.Decompress)) 
       {      
        // Copy the uncompressed file into the output stream. 
        dcmprss.CopyTo(outFile); 
        Console.WriteLine("Decompressed: {0}", fi.Name); 
       } 
      } 
     } 
    } 
} 

這也適用於GZipStream。

+0

@CSharpie:是的;他正在寫信給小溪。 – SLaks 2014-12-01 18:16:12

+0

順便提一句,'Path.GetFileNameWithoutExtension()'。 – SLaks 2014-12-01 18:16:55

+0

什麼是異常堆棧跟蹤? – SLaks 2014-12-01 18:17:16

回答

1

解壓縮流預計爲read from,未寫入。 (不像CryptoStream,支持讀/寫的所有四個組合和加密/解密)

您應該創建繞繞的輸入文件CryptoStreamMode.ReadDeflateStream,然後從直接複製到輸出流。

+0

@zaqk:請更正您的問題與糾正的代碼,以便第一個錯誤不混淆事情。 – EricLaw 2014-12-01 18:41:20

+0

@zaqk:您需要使CryptoStream從輸入流中讀取,而不是寫入輸出流。 – SLaks 2014-12-01 18:42:35

+0

@zaqk:這完全錯了。您需要在eachother和** input **文件周圍創建兩個流,然後直接複製到輸出流。 – SLaks 2014-12-01 18:54:15