2011-02-17 100 views
3

我希望能夠在數據流入/來自磁盤時加密/解密數據。 我知道我可以編寫自己的Stream並在那裏實現加密,但我寧願不冒險做錯。是否有一個類似於以下代碼的庫?是否有.NET加密庫作爲Stream實現AES 256加密?

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); 
+1

壓縮 – SLaks 2011-02-17 16:17:03

+0

後,您應該加密見過[很大的執行情況#1 AES加密的(http://stackoverflow.com/questions/165808/simple-2-way-encryption-for-c/212707#212707)本身。我從此開始使用它。檢查它是否適合你的目的。 – naveen 2011-02-17 16:30:16

回答

8

您正在尋找的RijndaelManagedCryptoStream類:

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)) { 
    ... 
}