using System; using System.IO; using System.Security.Cryptography; namespace FSI.Lib.EasyEncryption { /// /// Class that provides streaming decryption functionality. /// /// /// Using this class is the preferred way to decrypt values from a file or memory. /// Other decryption methods defer to this class for actual decryption. /// public class EncryptionReader : BinaryReader, IDisposable { private SymmetricAlgorithm Algorithm; private ICryptoTransform Decryptor; internal EncryptionReader(SymmetricAlgorithm algorithm, ICryptoTransform decryptor, Stream stream) : base(stream) { Algorithm = algorithm; Decryptor = decryptor; } /// /// Reads a DateTime value from the encrypted stream. /// /// The decrypted value. public DateTime ReadDateTime() { return new DateTime(ReadInt64()); } /// /// Reads a byte[] value from the encrypted stream. /// /// The decrypted values. public byte[] ReadByteArray() { int count = ReadInt32(); byte[] bytes = new byte[count]; if (count > 0) Read(bytes, 0, count); return bytes; } /// /// Reads a string[] value from the encrypted stream. /// /// The decrypted values. public string[] ReadStringArray() { int count = ReadInt32(); string[] strings = new string[count]; for (int i = 0; i < count; i++) strings[i] = ReadString(); return strings; } #region IDisposable implementation private bool disposed = false; // To detect redundant calls /// /// Releases all resources used by the current instance of the EncryptionReader class. /// public new void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// /// Releases the unmanaged resources used by the EncryptionReader 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); Decryptor.Dispose(); Algorithm.Dispose(); } } } /// /// Destructs this instance of EncryptionReader. /// ~EncryptionReader() { Dispose(false); } #endregion } }