/// <summary> /// Encrypt byte array /// </summary> /// <param name="value">Value to encrypt</param> /// <param name="key">Cryptographic key</param> /// <returns>Byte array containing Initialization Vector and encrypted value</returns> public byte[] EncryptBytes(byte[] value, byte[] key) { var algorithm = SymmetricAlgorithm.Create(typeof(TAlgorithm).Name); if (!algorithm.ValidKeySize(key.Length * 8)) { throw new ArgumentException("Invalid key size for specified symmetric algorithm [" + typeof(TAlgorithm).Name + "]."); } algorithm.GenerateIV(); algorithm.Key = key; using (var encryptor = algorithm.CreateEncryptor()) { using (var msEncrypt = new MemoryStream()) { using (var encryptStream = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (var plainStream = new MemoryStream(value)) { plainStream.CopyTo(encryptStream); encryptStream.FlushFinalBlock(); var encrypted = CryptographicValue <TAlgorithm> .Create(algorithm.IV, msEncrypt.ToArray()); algorithm.Clear(); return(encrypted.GetBinaryValue()); } } } } }
/// <summary> /// Decrypt byte array /// </summary> /// <param name="value">Value to encrypt</param> /// <param name="key">Encryption key</param> /// <returns><code>byte[]</code> containing decrypted data</returns> public byte[] DecryptBytes(byte[] value, byte[] key) { var algorithm = SymmetricAlgorithm.Create(typeof(TAlgorithm).Name); if (!algorithm.ValidKeySize(key.Length * 8)) { throw new ArgumentException("Invalid key size for specified symmetric algorithm [" + typeof(TAlgorithm).Name + "]."); } var cryptoValue = CryptographicValue <TAlgorithm> .Create(value); using (var decryptor = algorithm.CreateDecryptor(key, cryptoValue.Iv)) { using (var msDecrypt = new MemoryStream(cryptoValue.Value)) { using (var decryptStream = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (var resultStream = new MemoryStream()) { decryptStream.CopyTo(resultStream); algorithm.Clear(); return(resultStream.ToArray()); } } } } }