2014-12-01 8 views
1

나는 압축이 간단한 코드를 사용하여 한 가지에있는 파일을 암호화 할 :DeflateStream/GZipStream시키는 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에서도 작동합니다.

+0

@CSharpie : 예; 그는 시내에 글을 쓰고있다. – SLaks

+0

BTW,'Path.GetFileNameWithoutExtension()'. – SLaks

+0

예외 스택 추적이란 무엇입니까? – SLaks

답변

1

압축 해제 스트림은 read from이고 기록되지 않습니다.

(읽기/쓰기의 네 가지 조합을 지원하고/복호화를 암호화 CryptoStream 달리) 당신은 입력 파일 주위에 CryptoStreamMode.Read 스트림 주위 DeflateStream을 만들어야합니다, 출력 스트림에 직접적 복사.

+0

@zaqk : 수정 된 코드로 질문을 업데이트하여 첫 번째 실수가 혼란스럽지 않도록하십시오. – EricLaw

+0

@zaqk : CryptoStream을 입력 스트림에서 읽도록하고 출력 스트림에 쓰지 않아야합니다. – SLaks

+0

@zaqk : 그건 완전히 잘못되었습니다. 서로 주위에 스트림과 ** input ** 파일을 생성 한 다음 출력 스트림에 직접 복사해야합니다. – SLaks