首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DeflateStream / GZipStream到CryptoStream,反之亦然

DeflateStream / GZipStream到CryptoStream,反之亦然
EN

Stack Overflow用户
提问于 2014-12-01 18:12:55
回答 1查看 1.7K关注 0票数 2

通过使用以下简单代码,我想一次压缩和加密一个文件:

代码语言:javascript
复制
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());
                }
            }
        }
    }
}

下面的行将将加密和压缩的文件还原回原始文件:

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-01 18:25:33

解压缩流应该是读自,而不是写到的。(与CryptoStream不同,它支持读写和加密/解密的所有四个组合)

您应该围绕输入文件周围的一个DeflateStream流创建CryptoStreamMode.Read,然后将其直接复制到输出流中。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27234575

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档