我想使用以下简单的代码一次性压缩和加密文件:
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。
解压缩流应该被读取,而不是写入。 (与支持读/写和加密/解密所有四种组合的CryptoStream
不同)
应围绕输入文件周围的CryptoStreamMode.Read
流创建DeflateStream
,然后从该流直接复制到输出流。