SymmetricAlgorithmExtensions Class
Definition
- Namespace
- Bodu.Security.Cryptography.Extensions
- Assembly
- Bodu.Security.Cryptography.dll
- Package
- Bodu.Security.Cryptography 1.2.0
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
EncryptandDecryptoverloads 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 awaitableEncryptAsync/DecryptAsyncvariants. The buffer size defaults to DefaultBufferSize (80 KiB); callers can override it with the explicitbufferSizeoverload. 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
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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for decryption. Must not be null.
arraybyte[]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
algorithmis null.-or-
arrayis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for decryption. Must not be null.
arraybyte[]The input byte array to decrypt. Must not be null.
offsetintThe zero-based byte offset in
arrayat which to begin reading.
Returns
- byte[]
A new byte array containing the decrypted output.
Exceptions
- ArgumentNullException
algorithmis null.-or-
arrayis null.- ArgumentOutOfRangeException
offsetis negative or exceeds the length ofarray.
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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for decryption. Must not be null.
arraybyte[]The input byte array to decrypt. Must not be null.
offsetintThe zero-based byte offset in
arrayat which to begin reading.countintThe 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
algorithmis null.-or-
arrayis null.- ArgumentOutOfRangeException
offsetorcountis negative, or the range defined byoffsetandcountexceeds the bounds ofarray.
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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for decryption. Must not be null.
sourceStreamStreamThe stream to read encrypted data from. Must not be null.
targetStreamStreamThe 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, ortargetStreamis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for decryption. Must not be null.
sourceStreamStreamThe stream to read encrypted data from. Must not be null.
targetStreamStreamThe stream to write the decrypted output to. Must not be null.
bufferSizeintThe 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, ortargetStreamis null.- ArgumentOutOfRangeException
bufferSizeis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for decryption. Must not be null.
inputReadOnlyMemory<byte>The memory region containing the bytes to decrypt.
Returns
- byte[]
A new byte array containing the decrypted output.
Remarks
Delegates to Decrypt(SymmetricAlgorithm, ReadOnlySpan<byte>).
Exceptions
- ArgumentNullException
algorithmis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for decryption. Must not be null.
inputReadOnlySpan<byte>The span of input bytes to decrypt.
Returns
- byte[]
A new byte array containing the decrypted output.
Exceptions
- ArgumentNullException
algorithmis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for decryption. Must not be null.
sourceStreamStreamThe stream to read encrypted data from. Must not be null.
targetStreamStreamThe stream to write the decrypted output to. Must not be null.
bufferSizeintThe size, in bytes, of the read buffer. Must be greater than zero.
cancellationTokenCancellationTokenA token to monitor for cancellation requests.
Returns
Examples
using var aes = Aes.Create();
await aes.DecryptAsync(encryptedStream, decryptedStream, 4096, cancellationToken);
Exceptions
- ArgumentNullException
algorithm,sourceStream, ortargetStreamis null.- ArgumentOutOfRangeException
bufferSizeis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for decryption. Must not be null.
sourceStreamStreamThe stream to read encrypted data from. Must not be null.
targetStreamStreamThe stream to write the decrypted output to. Must not be null.
cancellationTokenCancellationTokenA token to monitor for cancellation requests.
Returns
Exceptions
- ArgumentNullException
algorithm,sourceStream, ortargetStreamis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for encryption. Must not be null.
arraybyte[]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
algorithmis null.-or-
arrayis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for encryption. Must not be null.
arraybyte[]The input byte array to encrypt. Must not be null.
offsetintThe zero-based byte offset in
arrayat which to begin reading.
Returns
- byte[]
A new byte array containing the encrypted output.
Exceptions
- ArgumentNullException
algorithmis null.-or-
arrayis null.- ArgumentOutOfRangeException
offsetis negative or exceeds the length ofarray.
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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for encryption. Must not be null.
arraybyte[]The input byte array to encrypt. Must not be null.
offsetintThe zero-based byte offset in
arrayat which to begin reading.countintThe 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
algorithmis null.-or-
arrayis null.- ArgumentOutOfRangeException
offsetorcountis negative, or the range defined byoffsetandcountexceeds the bounds ofarray.
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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for encryption. Must not be null.
sourceStreamStreamThe stream to read plaintext from. Must not be null.
targetStreamStreamThe 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, ortargetStreamis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for encryption. Must not be null.
sourceStreamStreamThe stream to read plaintext from. Must not be null.
targetStreamStreamThe stream to write the encrypted output to. Must not be null.
bufferSizeintThe 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, ortargetStreamis null.- ArgumentOutOfRangeException
bufferSizeis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for encryption. Must not be null.
inputReadOnlyMemory<byte>The memory region containing the bytes to encrypt.
Returns
- byte[]
A new byte array containing the encrypted output.
Remarks
Delegates to Encrypt(SymmetricAlgorithm, ReadOnlySpan<byte>).
Exceptions
- ArgumentNullException
algorithmis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for encryption. Must not be null.
inputReadOnlySpan<byte>The span of input bytes to encrypt.
Returns
- byte[]
A new byte array containing the encrypted output.
Exceptions
- ArgumentNullException
algorithmis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for encryption. Must not be null.
sourceStreamStreamThe stream to read plaintext from. Must not be null.
targetStreamStreamThe stream to write the encrypted output to. Must not be null.
bufferSizeintThe size, in bytes, of the read buffer. Must be greater than zero.
cancellationTokenCancellationTokenA token to monitor for cancellation requests.
Returns
Examples
using var aes = Aes.Create();
await aes.EncryptAsync(inputStream, outputStream, 4096, cancellationToken);
Exceptions
- ArgumentNullException
algorithm,sourceStream, ortargetStreamis null.- ArgumentOutOfRangeException
bufferSizeis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for encryption. Must not be null.
sourceStreamStreamThe stream to read plaintext from. Must not be null.
targetStreamStreamThe stream to write the encrypted output to. Must not be null.
cancellationTokenCancellationTokenA token to monitor for cancellation requests.
Returns
Exceptions
- ArgumentNullException
algorithm,sourceStream, ortargetStreamis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for decryption. Must not be null.
keybyte[]The secret key to use for the cryptographic operation.
ivbyte[]The initialization vector.
transformICryptoTransformWhen this method returns, contains the created ICryptoTransform if the operation succeeded; otherwise, null.
Returns
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
algorithmis null.
TryCreateDecryptor(SymmetricAlgorithm, out ICryptoTransform?)
public static bool TryCreateDecryptor(this SymmetricAlgorithm algorithm, out ICryptoTransform? transform)
Parameters
algorithmSymmetricAlgorithmThe symmetric algorithm to use for decryption. Must not be null.
transformICryptoTransformWhen this method returns, contains the created ICryptoTransform if the operation succeeded; otherwise, null.
Returns
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
algorithmis 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
algorithmSymmetricAlgorithmThe symmetric algorithm to use for encryption. Must not be null.
keybyte[]The secret key to use for the cryptographic operation.
ivbyte[]The initialization vector.
transformICryptoTransformWhen this method returns, contains the created ICryptoTransform if the operation succeeded; otherwise, null.
Returns
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
algorithmis null.
TryCreateEncryptor(SymmetricAlgorithm, out ICryptoTransform?)
public static bool TryCreateEncryptor(this SymmetricAlgorithm algorithm, out ICryptoTransform? transform)
Parameters
algorithmSymmetricAlgorithmThe symmetric algorithm to use for encryption. Must not be null.
transformICryptoTransformWhen this method returns, contains the created ICryptoTransform if the operation succeeded; otherwise, null.
Returns
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
algorithmis null.
Applies to
| Product | Versions |
|---|---|
| .NET | 8, 10 |