2014-12-01 99 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