public void EmptyKeyValueThrowsInvalidOperationException() { var credential = new Credential(() => new byte[0], SymmetricAlgorithm.Aes, 16); Action getKey = () => credential.GetKey(); getKey.ShouldThrow <InvalidOperationException>().WithMessage("The value returned from the key function must not be null or empty."); }
public void CanGetKey() { var credential = new Credential( () => Convert.FromBase64String("1J9Og / OaZKWdfdwM6jWMpvlr3q3o7r20xxFDN7TEj6s="), SymmetricAlgorithm.Aes, 16); var key = credential.GetKey(); key.Should().NotBeNull(); key.Length.Should().BeGreaterThan(0); }
/// <summary> /// Decrypts the specified cipher text. /// </summary> /// <param name="cipherText">The cipher text.</param> /// <returns>The decrypted value as a byte array.</returns> public byte[] Decrypt(byte[] cipherText) { if (cipherText is null) { throw new ArgumentNullException(nameof(cipherText)); } if (!cipherText.IsEncrypted()) { return(cipherText); } var decrypted = new List <byte>(cipherText.Length); using (var stream = new MemoryStream(cipherText)) { var decryptor = _algorithm.CreateDecryptor( _credential.GetKey(), stream.ReadIVFromCipherTextHeader()); using var cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read); const int bufferSize = 256; var buffer = new byte[bufferSize]; while (true) { var readBytes = cryptoStream.Read(buffer, 0, buffer.Length); if (readBytes > 0) { decrypted.AddRange(buffer.Take(readBytes)); } else { break; } } } return(decrypted.ToArray()); }