using System; using System.IO; using System.Security.Cryptography; namespace FSI.Lib.EasyEncryption { /// /// Class that provides streaming encryption functionality. /// /// /// Using this class is the preferred way to encrypt values to a file or memory. /// Other encryption methods defer to this class for actual encryption. Meta data /// that must be stored with the encrypted result is only stored once for all /// data in the stream. /// public class EncryptionWriter : BinaryWriter, IDisposable { private readonly SymmetricAlgorithm Algorithm; private readonly ICryptoTransform Encryptor; internal EncryptionWriter(SymmetricAlgorithm algorithm, ICryptoTransform encryptor, Stream stream) : base(stream) { Algorithm = algorithm; Encryptor = encryptor; } /// /// Writes a DateTime value to the encrypted stream. /// /// DateTime value to write. public void Write(DateTime value) { Write(value.Ticks); } /// /// Writes a byte array to the encrypted stream. /// /// /// Note: Hides BinaryWriter.Write(byte[]). /// /// byte[] values to write. public new void Write(byte[] value) { Write(value.Length); Write(value, 0, value.Length); } /// /// Writes a string to the encrypted stream. /// /// string[] values to write. public void Write(string[] value) { Write(value.Length); for (int i = 0; i < value.Length; i++) Write(value[i]); } #region IDisposable implementation private bool disposed = false; // To detect redundant calls /// /// Releases all resources used by the current instance of the EncryptionWriter class. /// public new void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// /// Releases the unmanaged resources used by the EncryptionWriter class and optionally /// releases the managed resources. /// /// true to release both managed and unmanaged resources; /// false to release only unmanaged resources. protected override void Dispose(bool disposing) { if (!disposed) { disposed = true; if (disposing) { // Dispose managed objects base.Dispose(true); Encryptor.Dispose(); Algorithm.Dispose(); } } } /// /// Destructs this instance of EncryptionWriter. /// ~EncryptionWriter() { Dispose(false); } #endregion } }