DeflateStream / GZipStream to CryptoStream and vice versa

☆樱花仙子☆ 提交于 2021-02-07 09:33:39

问题


I want to to compress and encrypt a file in one go by using this simple code:

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());
                }
            }
        }
    }
}

The following lines will restore the encrypted and compressed file back to the original:

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);
                }
            }
        }
    }
}

This works also with GZipStream.


回答1:


A decompressing stream is expected to be read from, not written to. (unlike a CryptoStream, which supports all four combinations of read/write and encrypt/decrypt)

You should create the DeflateStream around a CryptoStreamMode.Read stream around the input file, then copy from that directly to the output stream.



来源:https://stackoverflow.com/questions/27234575/deflatestream-gzipstream-to-cryptostream-and-vice-versa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!