c# - DeflateStream/GZipStream 到 CryptoStream,反之亦然

标签 c# rijndael gzipstream deflatestream 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。

最佳答案

解压流预计为read from ,未写入。 (与CryptoStream不同,它支持读/写和加密/解密的所有四种组合)

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

关于c# - DeflateStream/GZipStream 到 CryptoStream,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27234575/

相关文章:

c# - 无法使用 C# 解密使用 PHP 加密的数据 (Rijdael-128)

c# - 如何修复 Rijndael 解密中的 'Org.BouncyCaSTLe.Crypto.InvalidCipherTextException: ' pad block corrupted''

c# - 为什么我的C#gzip生成的文件比Fiddler或PHP大?

c# - 如何在没有第三方库的情况下序列化对象+压缩然后解压+反序列化?

.net - 如何使用 GZipStream 类压缩 GZip 文件中的多个文件?

c# - 'Text' 的 'asp:TextBox' 属性不允许子对象

c# - JSON反序列化Stack结构颠倒顺序

c# - Nest Client在Elasticsearch中进行相等查询

c# - 表格申请的字体选择

php - 解密在 GOLang 上用 PHP 解密的 AES-CBC-256 Mcrypt_RIJNDAEL