Table of Contents

SymmetricAlgorithmExtensions Class

Definition

Namespace
Bodu.Security.Cryptography.Extensions
Assembly
Bodu.Security.Cryptography.dll
Package
Bodu.Security.Cryptography 1.2.0
Source
SymmetricAlgorithmExtensions.Decrypt.cs

Extends SymmetricAlgorithm with one-shot encrypt/decrypt of buffers, stream-to-stream pipelines, awaitable async variants, and try-pattern transform creation that surfaces validation failures without exceptions.

public static class SymmetricAlgorithmExtensions
Inheritance
SymmetricAlgorithmExtensions
Inherited Members

Remarks

SymmetricAlgorithm ships with the building blocks - CreateEncryptor, CreateDecryptor, and CryptoStream - but stops short of the operations that callers actually want to invoke: "encrypt this byte array", "decrypt this stream into that one", or "give me back the encryptor only if the key/IV check out". Production code that does this work tends to repeat the same setup: instantiate the transform, wrap it in a CryptoStream, drain the source, dispose everything in the right order. This class collapses that into a single call per scenario, with overloads aligned to the input shape.

The API surface clusters into three groups:

  • Encrypt / Decrypt - one-shot Encrypt and Decrypt overloads accepting byte[], a slice (offset/count), ReadOnlySpan<T>, or ReadOnlyMemory<T>, returning the result as a freshly allocated array. Use these when the entire payload fits in memory.
  • Encrypt / Decrypt - stream Encrypt(sourceStream, targetStream) / Decrypt(sourceStream, targetStream) with awaitable EncryptAsync / DecryptAsync variants. The buffer size defaults to DefaultBufferSize (80 KiB); callers can override it with the explicit bufferSize overload. Streams are not disposed by these methods.
  • Try-pattern transform creation TryCreateEncryptor / TryCreateDecryptor - surface key/IV validation failures as a false return rather than a CryptographicException. Useful when accepting key material from configuration or user input.

All operations honor the algorithm's configured Mode and Padding; for AEAD modes (GCM, CCM, EAX, …) prefer the dedicated AeadBlockCipherModeTransformExtensions in the same namespace, which handles associated data and tag layout. Async overloads honor CancellationToken at every read boundary. SymmetricAlgorithm instances are not thread-safe; share them only behind explicit synchronization.

using System.Security.Cryptography;
using Bodu.Security.Cryptography.Extensions;

using Aes aes = Aes.Create();
aes.Key = key;
aes.IV = iv;

// 1. One-shot encrypt of an in-memory span; one-shot decrypt back.
byte[] ciphertext = aes.Encrypt(plaintext.AsSpan());
byte[] roundTrip = aes.Decrypt(ciphertext);

// 2. Stream-encrypt a large file with the default 80 KiB buffer.
using FileStream src = File.OpenRead("plain.bin");
using FileStream dst = File.Create("cipher.bin");
int bytesWritten = aes.Encrypt(src, dst);

// 3. Validate caller-supplied key material without catching CryptographicException.
if (!aes.TryCreateDecryptor(suppliedKey, suppliedIv, out ICryptoTransform? decryptor))
    return BadRequest("invalid key/iv combination");
using (decryptor) { /* … decrypt with the validated transform … */ }

Fields

DefaultBufferSize

The default buffer size, in bytes, used when reading from or writing to streams during encryption and decryption operations.

public const int DefaultBufferSize = 81920

Field Value

int

Methods

Decrypt(SymmetricAlgorithm, byte[])

Decrypts the entire contents of a byte array using the specified symmetric algorithm.

public static byte[] Decrypt(this SymmetricAlgorithm algorithm, byte[] array)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for decryption. Must not be null.

array byte[]

The input byte array to decrypt. Must not be null.

Returns

byte[]

A new byte array containing the decrypted output.

Remarks

Equivalent to calling Decrypt(array, 0, array.Length).

Exceptions

ArgumentNullException

algorithm is null.

-or-

array is null.

Decrypt(SymmetricAlgorithm, byte[], int)

Decrypts a portion of a byte array beginning at the specified offset and continuing to the end of the array.

public static byte[] Decrypt(this SymmetricAlgorithm algorithm, byte[] array, int offset)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for decryption. Must not be null.

array byte[]

The input byte array to decrypt. Must not be null.

offset int

The zero-based byte offset in array at which to begin reading.

Returns

byte[]

A new byte array containing the decrypted output.

Exceptions

ArgumentNullException

algorithm is null.

-or-

array is null.
ArgumentOutOfRangeException

offset is negative or exceeds the length of array.

Decrypt(SymmetricAlgorithm, byte[], int, int)

Decrypts a contiguous region of a byte array using the specified symmetric algorithm.

public static byte[] Decrypt(this SymmetricAlgorithm algorithm, byte[] array, int offset, int count)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for decryption. Must not be null.

array byte[]

The input byte array to decrypt. Must not be null.

offset int

The zero-based byte offset in array at which to begin reading.

count int

The number of bytes to decrypt.

Returns

byte[]

A new byte array containing the decrypted output.

Examples

using var aes = Aes.Create();
byte[] decrypted = aes.Decrypt(cipherText, 0, cipherText.Length);

Exceptions

ArgumentNullException

algorithm is null.

-or-

array is null.
ArgumentOutOfRangeException

offset or count is negative, or the range defined by offset and count exceeds the bounds of array.

Decrypt(SymmetricAlgorithm, Stream, Stream)

Decrypts data read from a source stream and writes the decrypted output to a target stream, using the default buffer size.

public static int Decrypt(this SymmetricAlgorithm algorithm, Stream sourceStream, Stream targetStream)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for decryption. Must not be null.

sourceStream Stream

The stream to read encrypted data from. Must not be null.

targetStream Stream

The stream to write the decrypted output to. Must not be null.

Returns

int

The total number of encrypted bytes read from sourceStream.

Exceptions

ArgumentNullException

algorithm, sourceStream, or targetStream is null.

Decrypt(SymmetricAlgorithm, Stream, Stream, int)

Decrypts data read from a source stream and writes the decrypted output to a target stream, using the specified buffer size.

public static int Decrypt(this SymmetricAlgorithm algorithm, Stream sourceStream, Stream targetStream, int bufferSize)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for decryption. Must not be null.

sourceStream Stream

The stream to read encrypted data from. Must not be null.

targetStream Stream

The stream to write the decrypted output to. Must not be null.

bufferSize int

The size, in bytes, of the read buffer. Must be greater than zero.

Returns

int

The total number of encrypted bytes read from sourceStream.

Examples

using var aes = Aes.Create();
using var input = File.OpenRead("output.enc");
using var output = File.Create("decrypted.txt");
int bytesRead = aes.Decrypt(input, output, 4096);

Exceptions

ArgumentNullException

algorithm, sourceStream, or targetStream is null.

ArgumentOutOfRangeException

bufferSize is less than or equal to zero.

Decrypt(SymmetricAlgorithm, ReadOnlyMemory<byte>)

Decrypts a read-only memory region using the specified symmetric algorithm.

public static byte[] Decrypt(this SymmetricAlgorithm algorithm, ReadOnlyMemory<byte> input)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for decryption. Must not be null.

input ReadOnlyMemory<byte>

The memory region containing the bytes to decrypt.

Returns

byte[]

A new byte array containing the decrypted output.

Remarks

Exceptions

ArgumentNullException

algorithm is null.

Decrypt(SymmetricAlgorithm, ReadOnlySpan<byte>)

Decrypts a read-only span of bytes using the specified symmetric algorithm.

public static byte[] Decrypt(this SymmetricAlgorithm algorithm, ReadOnlySpan<byte> input)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for decryption. Must not be null.

input ReadOnlySpan<byte>

The span of input bytes to decrypt.

Returns

byte[]

A new byte array containing the decrypted output.

Exceptions

ArgumentNullException

algorithm is null.

DecryptAsync(SymmetricAlgorithm, Stream, Stream, int, CancellationToken)

Asynchronously decrypts data read from a source stream and writes the decrypted output to a target stream, using the specified buffer size.

public static Task DecryptAsync(this SymmetricAlgorithm algorithm, Stream sourceStream, Stream targetStream, int bufferSize, CancellationToken cancellationToken = default)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for decryption. Must not be null.

sourceStream Stream

The stream to read encrypted data from. Must not be null.

targetStream Stream

The stream to write the decrypted output to. Must not be null.

bufferSize int

The size, in bytes, of the read buffer. Must be greater than zero.

cancellationToken CancellationToken

A token to monitor for cancellation requests.

Returns

Task

A Task representing the asynchronous decryption operation.

Examples

using var aes = Aes.Create();
await aes.DecryptAsync(encryptedStream, decryptedStream, 4096, cancellationToken);

Exceptions

ArgumentNullException

algorithm, sourceStream, or targetStream is null.

ArgumentOutOfRangeException

bufferSize is less than or equal to zero.

OperationCanceledException

The operation was canceled via cancellationToken.

DecryptAsync(SymmetricAlgorithm, Stream, Stream, CancellationToken)

Asynchronously decrypts data read from a source stream and writes the decrypted output to a target stream, using the default buffer size.

public static Task DecryptAsync(this SymmetricAlgorithm algorithm, Stream sourceStream, Stream targetStream, CancellationToken cancellationToken = default)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for decryption. Must not be null.

sourceStream Stream

The stream to read encrypted data from. Must not be null.

targetStream Stream

The stream to write the decrypted output to. Must not be null.

cancellationToken CancellationToken

A token to monitor for cancellation requests.

Returns

Task

A Task representing the asynchronous decryption operation.

Exceptions

ArgumentNullException

algorithm, sourceStream, or targetStream is null.

OperationCanceledException

The operation was canceled via cancellationToken.

Encrypt(SymmetricAlgorithm, byte[])

Encrypts the entire contents of a byte array using the specified symmetric algorithm.

public static byte[] Encrypt(this SymmetricAlgorithm algorithm, byte[] array)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for encryption. Must not be null.

array byte[]

The input byte array to encrypt. Must not be null.

Returns

byte[]

A new byte array containing the encrypted output.

Remarks

Equivalent to calling Encrypt(array, 0, array.Length).

Exceptions

ArgumentNullException

algorithm is null.

-or-

array is null.

Encrypt(SymmetricAlgorithm, byte[], int)

Encrypts a portion of a byte array beginning at the specified offset and continuing to the end of the array.

public static byte[] Encrypt(this SymmetricAlgorithm algorithm, byte[] array, int offset)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for encryption. Must not be null.

array byte[]

The input byte array to encrypt. Must not be null.

offset int

The zero-based byte offset in array at which to begin reading.

Returns

byte[]

A new byte array containing the encrypted output.

Exceptions

ArgumentNullException

algorithm is null.

-or-

array is null.
ArgumentOutOfRangeException

offset is negative or exceeds the length of array.

Encrypt(SymmetricAlgorithm, byte[], int, int)

Encrypts a contiguous region of a byte array using the specified symmetric algorithm.

public static byte[] Encrypt(this SymmetricAlgorithm algorithm, byte[] array, int offset, int count)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for encryption. Must not be null.

array byte[]

The input byte array to encrypt. Must not be null.

offset int

The zero-based byte offset in array at which to begin reading.

count int

The number of bytes to encrypt.

Returns

byte[]

A new byte array containing the encrypted output.

Examples

using var aes = Aes.Create();
byte[] cipherText = aes.Encrypt(data, 0, data.Length);

Exceptions

ArgumentNullException

algorithm is null.

-or-

array is null.
ArgumentOutOfRangeException

offset or count is negative, or the range defined by offset and count exceeds the bounds of array.

Encrypt(SymmetricAlgorithm, Stream, Stream)

Encrypts data read from a source stream and writes the encrypted output to a target stream, using the default buffer size.

public static int Encrypt(this SymmetricAlgorithm algorithm, Stream sourceStream, Stream targetStream)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for encryption. Must not be null.

sourceStream Stream

The stream to read plaintext from. Must not be null.

targetStream Stream

The stream to write the encrypted output to. Must not be null.

Returns

int

The total number of plaintext bytes read from sourceStream.

Exceptions

ArgumentNullException

algorithm, sourceStream, or targetStream is null.

Encrypt(SymmetricAlgorithm, Stream, Stream, int)

Encrypts data read from a source stream and writes the encrypted output to a target stream, using the specified buffer size.

public static int Encrypt(this SymmetricAlgorithm algorithm, Stream sourceStream, Stream targetStream, int bufferSize)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for encryption. Must not be null.

sourceStream Stream

The stream to read plaintext from. Must not be null.

targetStream Stream

The stream to write the encrypted output to. Must not be null.

bufferSize int

The size, in bytes, of the read buffer. Must be greater than zero.

Returns

int

The total number of plaintext bytes read from sourceStream.

Examples

using var aes = Aes.Create();
using var input = File.OpenRead("input.txt");
using var output = File.Create("output.enc");
int bytesRead = aes.Encrypt(input, output, 4096);

Exceptions

ArgumentNullException

algorithm, sourceStream, or targetStream is null.

ArgumentOutOfRangeException

bufferSize is less than or equal to zero.

Encrypt(SymmetricAlgorithm, ReadOnlyMemory<byte>)

Encrypts a read-only memory region using the specified symmetric algorithm.

public static byte[] Encrypt(this SymmetricAlgorithm algorithm, ReadOnlyMemory<byte> input)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for encryption. Must not be null.

input ReadOnlyMemory<byte>

The memory region containing the bytes to encrypt.

Returns

byte[]

A new byte array containing the encrypted output.

Remarks

Exceptions

ArgumentNullException

algorithm is null.

Encrypt(SymmetricAlgorithm, ReadOnlySpan<byte>)

Encrypts a read-only span of bytes using the specified symmetric algorithm.

public static byte[] Encrypt(this SymmetricAlgorithm algorithm, ReadOnlySpan<byte> input)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for encryption. Must not be null.

input ReadOnlySpan<byte>

The span of input bytes to encrypt.

Returns

byte[]

A new byte array containing the encrypted output.

Exceptions

ArgumentNullException

algorithm is null.

EncryptAsync(SymmetricAlgorithm, Stream, Stream, int, CancellationToken)

Asynchronously encrypts data read from a source stream and writes the encrypted output to a target stream, using the specified buffer size.

public static Task EncryptAsync(this SymmetricAlgorithm algorithm, Stream sourceStream, Stream targetStream, int bufferSize, CancellationToken cancellationToken = default)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for encryption. Must not be null.

sourceStream Stream

The stream to read plaintext from. Must not be null.

targetStream Stream

The stream to write the encrypted output to. Must not be null.

bufferSize int

The size, in bytes, of the read buffer. Must be greater than zero.

cancellationToken CancellationToken

A token to monitor for cancellation requests.

Returns

Task

A Task representing the asynchronous encryption operation.

Examples

using var aes = Aes.Create();
await aes.EncryptAsync(inputStream, outputStream, 4096, cancellationToken);

Exceptions

ArgumentNullException

algorithm, sourceStream, or targetStream is null.

ArgumentOutOfRangeException

bufferSize is less than or equal to zero.

OperationCanceledException

The operation was canceled via cancellationToken.

EncryptAsync(SymmetricAlgorithm, Stream, Stream, CancellationToken)

Asynchronously encrypts data read from a source stream and writes the encrypted output to a target stream, using the default buffer size.

public static Task EncryptAsync(this SymmetricAlgorithm algorithm, Stream sourceStream, Stream targetStream, CancellationToken cancellationToken = default)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for encryption. Must not be null.

sourceStream Stream

The stream to read plaintext from. Must not be null.

targetStream Stream

The stream to write the encrypted output to. Must not be null.

cancellationToken CancellationToken

A token to monitor for cancellation requests.

Returns

Task

A Task representing the asynchronous encryption operation.

Exceptions

ArgumentNullException

algorithm, sourceStream, or targetStream is null.

OperationCanceledException

The operation was canceled via cancellationToken.

TryCreateDecryptor(SymmetricAlgorithm, byte[], byte[], out ICryptoTransform?)

Attempts to create a decryptor using the specified decryption key and initialization vector (IV).

public static bool TryCreateDecryptor(this SymmetricAlgorithm algorithm, byte[] key, byte[] iv, out ICryptoTransform? transform)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for decryption. Must not be null.

key byte[]

The secret key to use for the cryptographic operation.

iv byte[]

The initialization vector.

transform ICryptoTransform

When this method returns, contains the created ICryptoTransform if the operation succeeded; otherwise, null.

Returns

bool

true if the decryptor was created successfully; otherwise, false.

Remarks

This method wraps CreateDecryptor(byte[], byte[]) in a try/catch block. Any exception raised by the underlying algorithm - for example, due to an invalid key length or unsupported IV size - is suppressed and results in a false return value.

Exceptions

ArgumentNullException

algorithm is null.

TryCreateDecryptor(SymmetricAlgorithm, out ICryptoTransform?)

Attempts to create a decryptor using the algorithm's current Key and IV values.

public static bool TryCreateDecryptor(this SymmetricAlgorithm algorithm, out ICryptoTransform? transform)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for decryption. Must not be null.

transform ICryptoTransform

When this method returns, contains the created ICryptoTransform if the operation succeeded; otherwise, null.

Returns

bool

true if the decryptor was created successfully; otherwise, false.

Remarks

Use this overload when the algorithm instance has already been configured with a key and IV. Any exception raised by the underlying algorithm is suppressed and results in a false return value.

Exceptions

ArgumentNullException

algorithm is null.

TryCreateEncryptor(SymmetricAlgorithm, byte[], byte[], out ICryptoTransform?)

Attempts to create an encryptor using the specified encryption key and initialization vector (IV).

public static bool TryCreateEncryptor(this SymmetricAlgorithm algorithm, byte[] key, byte[] iv, out ICryptoTransform? transform)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for encryption. Must not be null.

key byte[]

The secret key to use for the cryptographic operation.

iv byte[]

The initialization vector.

transform ICryptoTransform

When this method returns, contains the created ICryptoTransform if the operation succeeded; otherwise, null.

Returns

bool

true if the encryptor was created successfully; otherwise, false.

Remarks

This method wraps CreateEncryptor(byte[], byte[]) in a try/catch block. Any exception raised by the underlying algorithm - for example, due to an invalid key length or unsupported IV size - is suppressed and results in a false return value.

Exceptions

ArgumentNullException

algorithm is null.

TryCreateEncryptor(SymmetricAlgorithm, out ICryptoTransform?)

Attempts to create an encryptor using the algorithm's current Key and IV values.

public static bool TryCreateEncryptor(this SymmetricAlgorithm algorithm, out ICryptoTransform? transform)

Parameters

algorithm SymmetricAlgorithm

The symmetric algorithm to use for encryption. Must not be null.

transform ICryptoTransform

When this method returns, contains the created ICryptoTransform if the operation succeeded; otherwise, null.

Returns

bool

true if the encryptor was created successfully; otherwise, false.

Remarks

Use this overload when the algorithm instance has already been configured, for example via GenerateKey() and GenerateIV(). Any exception raised by the underlying algorithm is suppressed and results in a false return value.

Exceptions

ArgumentNullException

algorithm is null.

Applies to

ProductVersions
.NET8, 10