CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 564

564
Chương 14: Mật mã

Stream destFile =

new FileStream(destFileName, FileMode.Create,

FileAccess.Write);

// Tạo một giải thuật Triple DES mới để mật hóa file.

using(SymmetricAlgorithm alg =

SymmetricAlgorithm.Create("3DES")){

// Cấu hình thuộc tính Key và IV của giải thuật.

alg.Key = key;

alg.IV = iv;

// Tạo một CryptoStream để mật hóa nội dung của

// Stream nguồn khi nó được đọc. Gọi phương thức

// CreateEncryptor của SymmetricAlgorithm

// để nhận thể hiện ICryptoTransform và

// truyền nó cho CryptoStream.

CryptoStream cryptoStream = new CryptoStream(srcFile,

alg.CreateEncryptor(),

CryptoStreamMode.Read);

// Khai báo bộ đệm dùng để đọc dữ liệu từ file nguồn

// thông qua CryptoStream và ghi nó ra file đích.

int bufferLength;

byte[] buffer = new byte[1024];

// Đọc file nguồn (từng khối 1024 byte) và ghi phiên bản

// đã-được-mật-hóa ra file đích.

do {

bufferLength = cryptoStream.Read(buffer, 0, 1024);

destFile.Write(buffer, 0, bufferLength);

} while (bufferLength > 0);

// Đóng stream và xóa các dữ liệu bí mật.

destFile.Flush();

Array.Clear(key,0,key.Length);