2

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

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。

4

1 回答 1

2

解压缩流应从 读取,而不是写入。(与 a 不同CryptoStream,它支持读/写和加密/解密的所有四种组合)

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

于 2014-12-01T18:25:33.010 回答