/// <summary> /// Asynchronously decrypts the specified <see cref="EncryptionResult"/> that was obtained using <see cref="ISymmetricCryptography.EncryptAsync(byte[])"/>. /// </summary> /// <param name="encryptionResult">The <see cref="EncryptionResult"/> that was obtained using <see cref="ISymmetricCryptography.EncryptAsync(byte[])"/>.</param> /// <returns>Decrypted <c>byte[]</c> or <c>null</c> if decryption failed.</returns> public async Task <byte[]> DecryptAsync(EncryptionResult encryptionResult) { int encryptedBytesLength = encryptionResult?.EncryptedData?.Length ?? 0; if (encryptedBytesLength == 0) { return(Array.Empty <byte>()); } byte[] result; await using var output = new MemoryStream(encryptedBytesLength); await using var input = new MemoryStream(encryptionResult.EncryptedData); try { using var aes = new AesManaged { KeySize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7, IV = encryptionResult.IV, Key = encryptionResult.Key }; using ICryptoTransform decryptor = aes.CreateDecryptor(); await using var cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read); await cryptoStream.CopyToAsync(output).ConfigureAwait(false); await cryptoStream.FlushAsync(); result = output.ToArray(); } catch { result = null; } return(result); }
/// <summary> /// Decrypts the specified <see cref="EncryptionResult"/> that was obtained using <see cref="ISymmetricCryptography.Encrypt(byte[])"/>. /// </summary> /// <param name="encryptionResult">The <see cref="EncryptionResult"/> that was obtained using <see cref="ISymmetricCryptography.Encrypt(byte[])"/>.</param> /// <returns>Decrypted <c>byte[]</c> array or <c>null</c> if decryption failed.</returns> public byte[] Decrypt(EncryptionResult encryptionResult) { int encryptedBytesLength = encryptionResult?.EncryptedData?.Length ?? 0; if (encryptedBytesLength == 0) { return(Array.Empty <byte>()); } byte[] result; AesManaged aes = null; ICryptoTransform decryptor = null; try { aes = new AesManaged { KeySize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7, IV = encryptionResult.IV, Key = encryptionResult.Key }; decryptor = aes.CreateDecryptor(); result = decryptor.TransformFinalBlock(encryptionResult.EncryptedData, 0, encryptedBytesLength); } catch { result = null; } finally { aes?.Dispose(); decryptor?.Dispose(); } return(result); }