【问题标题】:DeflateStream / GZipStream to CryptoStream and vice versaDeflateStream / GZipStream 到 CryptoStream,反之亦然
【发布时间】:2014-12-01 18:12:55
【问题描述】:

我想用这个简单的代码一次性压缩和加密一个文件:

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。

【问题讨论】:

  • @CSharpie:是的;他正在写信给流。
  • 顺便说一句,Path.GetFileNameWithoutExtension().
  • 异常堆栈跟踪是什么?
  • 改正代码后,反之亦然。

标签: c# rijndael gzipstream deflatestream cryptostream


【解决方案1】:

解压缩流应该是read from,而不是写入。 (不像CryptoStream,它支持读/写和加密/解密的所有四种组合)

您应该围绕输入文件的CryptoStreamMode.Read 流创建DeflateStream,然后从该流直接复制到输出流。

【讨论】:

  • @zaqk:请使用更正后的代码更新您的问题,以免第一个错误造成混乱。
  • @zaqk:你需要让 CryptoStream 从输入流中读取,而不是写入输出流。
  • @zaqk:那是完全错误的。您需要围绕彼此和 input 文件创建两个流,然后直接复制到输出流。
  • @SLaks:谢谢!!这对我有帮助!
猜你喜欢
  • 1970-01-01
  • 2011-02-05
  • 2014-11-08
  • 2012-02-16
  • 2013-08-16
  • 2012-06-27
  • 2017-02-05
  • 2012-12-01
  • 2012-02-05
相关资源
最近更新 更多