5

I'd like to be able to encrypt / decrypt data as it's streamed to/from disk. I know I could write my own Stream and implement the encryption there, but I'd rather not risk doing it wrong. Is there a library that works in a similar way to the following code?

byte[] encryptionKey = ;
byte[] initVector = ;

var fileStream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write);
var encryptionStream = new AesEncryptionStream(fileStream, initVector, encryptionKey);
var gzStream = new GZipStream(encryptionStream, CompressionMode.Compress);
var writer = new BinaryWriter(gzStream);
ScArcher2
  • 85,501
  • 44
  • 121
  • 160
  • 1
    You should encrypt after compressing – SLaks Feb 17 '11 at 16:17
  • Have seen [a great implementation of AES Encryption at Stackoverflow](http://stackoverflow.com/questions/165808/simple-2-way-encryption-for-c/212707#212707) itself. I am using it ever since. Check if it suits your purpose. – naveen Feb 17 '11 at 16:30

1 Answers1

10

You're looking for the RijndaelManaged and CryptoStream classes:

var aes = new RijndaelManaged { Key = ..., IV = ... };

using (var encryptor = aes.CreateEncryptor()) 
using (var cryptoStream = new CryptoStream(gzStream, encryptor, CryptoStreamMode.Write))
using (var writer = new BinaryWriter(cryptoStream)) {
    ...
}
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • @SLaks: is using necessary on CryptoStream? btw congrats on being elected as a mod.my vote would need a treat. :) – naveen Feb 17 '11 at 16:35
  • 1
    "using" is not required, but it's a good practice with short-lived disposables like this. If you don't use using, make sure you dispose of all these when you're done. I think all of these just MIGHT implement a finalizer, but best not to test that. – KeithS Feb 17 '11 at 16:44
  • I asked these because a guy noted in a comment(link in my answer) that "there's no benefit to Disposing of MemoryStreams -- they're not like normal streams that hold an OS resource -- they just hold a buffer object that will be collected as all other in-memory objects will be" How valid is this? – naveen Feb 17 '11 at 16:48
  • 1
    @yet: He's right. However, CryptoStreams aren't MemoryStreams. Dispose calls FlushFinalBlock if necessary, and clears sensitive data. – SLaks Feb 17 '11 at 16:48
  • @Keith: Here, it is required. Otherwise, the final chunk won't be written. – SLaks Feb 17 '11 at 16:50
  • @SLaks: well, flushing/closing the CryptoStream manually would do the same, yes? I find it hard to believe that with the functionality provided by Stream, there's only one pattern for use of a CryptoStream that actually works. – KeithS Feb 17 '11 at 17:20