ICryptoTransformExtensions Class
Definition
- Namespace
- Bodu.Security.Cryptography.Extensions
- Assembly
- Bodu.Security.Cryptography.dll
- Package
- Bodu.Security.Cryptography 1.2.0
Extends ICryptoTransform with one-shot, span/memory-aware, stream-to-stream, and async transform helpers - sized buffers, finalization, and stream pumping rolled into single calls.
public static class ICryptoTransformExtensions
- Inheritance
-
ICryptoTransformExtensions
- Inherited Members
Remarks
ICryptoTransform is the contract that every block-cipher encryptor or decryptor implements, but its
raw API forces callers to size output buffers, allocate result arrays, distinguish intermediate
TransformBlock calls from the final TransformFinalBlock, and reset the transform between messages.
This class wraps those operations behind two verb-led names - Transform for whole-input processing and
TransformFinalBlock for finalization - that hide the buffering arithmetic and give the caller back a
correctly sized result.
The API surface clusters into four groups:
- One-shot in-memory
Transformoverloads that accept a byte array, an array slice (offset/count), a ReadOnlySpan<T>, or a ReadOnlyMemory<T> and return a freshly allocated output array. Use these when the entire input fits in memory. - Caller-supplied buffers
Transform(input, destination)overloads for span and memory destinations - for hot paths that want to reuse a pre-allocated output buffer and havedestinationwritten in place. The return value is the number of bytes written. - Stream pumping
Transform(sourceStream, targetStream, bufferSize)and the awaitableTransformAsyncoverloads, for cases where the input is a stream that should not be fully buffered. The extension drives the read/transform/write loop with a tunable buffer. - Finalization
TransformFinalBlockoverloads that mirror the same input shapes (no-arg, byte array, slice, span, memory) for emitting the final, padded block.
ICryptoTransform instances are stateful and single-use within a message - once TransformFinalBlock(byte[], int, int) has run, the transform should be disposed and a fresh one created for the next message. None of these helpers dispose the transform or the supplied streams; the caller owns the lifetime. Methods that allocate a result array always return exactly the number of bytes produced. Async overloads honor CancellationToken at every read boundary.
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 a span into a new byte[].
using ICryptoTransform encryptor = aes.CreateEncryptor();
byte[] ciphertext = encryptor.Transform(plaintext.AsSpan());
// 2. Stream-encrypt a large file end to end with a 64 KiB buffer.
using FileStream src = File.OpenRead("plain.bin");
using FileStream dst = File.Create("cipher.bin");
using ICryptoTransform e2 = aes.CreateEncryptor();
int written = e2.Transform(src, dst, bufferSize: 64 * 1024);
// 3. Cancellable async stream transform, e.g. when piping HTTP content.
using ICryptoTransform e3 = aes.CreateEncryptor();
await e3.TransformAsync(networkStream, output, bufferSize: 16 * 1024, cancellationToken);
Methods
Transform(ICryptoTransform, byte[])
Transforms the entire input byte array using the specified cryptographic transform.
public static byte[] Transform(this ICryptoTransform cryptoTransform, byte[] array)
Parameters
cryptoTransformICryptoTransformThe cryptographic transform to apply. Must not be null.
arraybyte[]The input byte array to transform. Must not be null.
Returns
- byte[]
A new byte array containing the transformed output.
Remarks
This overload is equivalent to calling Transform(array, 0, array.Length).
Exceptions
- ArgumentNullException
Thrown when
cryptoTransformorarrayis null.
Transform(ICryptoTransform, byte[], int, int)
Transforms a portion of the specified byte array using the given cryptographic transform.
public static byte[] Transform(this ICryptoTransform cryptoTransform, byte[] array, int offset, int count)
Parameters
cryptoTransformICryptoTransformThe cryptographic transform to apply. Must not be null.
arraybyte[]The input byte array containing the data to transform. Must not be null.
offsetintThe zero-based index in
arrayat which to begin reading.countintThe number of bytes to transform.
Returns
- byte[]
A new byte array containing the transformed output.
Examples
using var aes = Aes.Create();
byte[] encrypted = aes.CreateEncryptor().Transform(data, 0, data.Length);
Exceptions
- ArgumentNullException
Thrown when
cryptoTransformorarrayis null.- ArgumentOutOfRangeException
Thrown when
offsetorcountis negative, or exceeds the bounds ofarray.- ArgumentException
Thrown when the sum of
offsetandcountexceeds the length ofarray.
Transform(ICryptoTransform, Stream, Stream, int)
Applies the cryptographic transform to data read from sourceStream and writes the result to
targetStream using the specified buffer size.
public static int Transform(this ICryptoTransform transform, Stream sourceStream, Stream targetStream, int bufferSize)
Parameters
transformICryptoTransformThe cryptographic transform to apply. Must not be null.
sourceStreamStreamThe stream to read untransformed data from. Must not be null.
targetStreamStreamThe stream to write transformed data to. Must not be null.
bufferSizeintThe size, in bytes, of the temporary read buffer. Must be greater than zero.
Returns
- int
The total number of bytes read from
sourceStream.
Examples
using var aes = Aes.Create();
using var decryptor = aes.CreateDecryptor();
long bytesRead = decryptor.Transform(encryptedStream, outputStream, 81920);
Exceptions
- ArgumentNullException
Thrown when
transform,sourceStream, ortargetStreamis null.- ArgumentOutOfRangeException
Thrown when
bufferSizeis less than or equal to zero.
Transform(ICryptoTransform, ReadOnlyMemory<byte>)
Transforms a memory region using the specified cryptographic transform.
public static byte[] Transform(this ICryptoTransform cryptoTransform, ReadOnlyMemory<byte> input)
Parameters
cryptoTransformICryptoTransformThe cryptographic transform to apply. Must not be null.
inputReadOnlyMemory<byte>The memory region of input bytes to transform.
Returns
- byte[]
A new byte array containing the transformed output.
Remarks
This overload delegates to Transform(ICryptoTransform, ReadOnlySpan<byte>).
Exceptions
- ArgumentNullException
Thrown when
cryptoTransformis null.
Transform(ICryptoTransform, ReadOnlyMemory<byte>, Memory<byte>)
Transforms the input memory region and writes the result into the destination memory region.
public static int Transform(this ICryptoTransform transform, ReadOnlyMemory<byte> input, Memory<byte> destination)
Parameters
transformICryptoTransformThe cryptographic transform to apply. Must not be null.
inputReadOnlyMemory<byte>The memory region containing the input data.
destinationMemory<byte>The memory region to receive the transformed output.
Returns
- int
The number of bytes written to
destination.
Remarks
This overload delegates to Transform(ICryptoTransform, ReadOnlySpan<byte>, Span<byte>).
Exceptions
- ArgumentNullException
Thrown when
transformis null.- ArgumentException
Thrown when
destinationis too small to hold the transformed output.
Transform(ICryptoTransform, ReadOnlySpan<byte>)
Transforms a span of bytes using the specified cryptographic transform.
public static byte[] Transform(this ICryptoTransform cryptoTransform, ReadOnlySpan<byte> input)
Parameters
cryptoTransformICryptoTransformThe cryptographic transform to apply. Must not be null.
inputReadOnlySpan<byte>The span of input bytes to transform.
Returns
- byte[]
A new byte array containing the transformed output.
Exceptions
- ArgumentNullException
Thrown when
cryptoTransformis null.
Transform(ICryptoTransform, ReadOnlySpan<byte>, Span<byte>)
Transforms the input span and writes the result into the specified destination span.
public static int Transform(this ICryptoTransform transform, ReadOnlySpan<byte> input, Span<byte> destination)
Parameters
transformICryptoTransformThe cryptographic transform to apply. Must not be null.
inputReadOnlySpan<byte>The input span to transform.
destinationSpan<byte>The destination span to receive the transformed output.
Returns
- int
The number of bytes written to
destination.
Remarks
The transformed output is written into destination rather than returned as a new allocation,
making this overload suitable for scenarios where the caller manages buffer lifetimes.
Exceptions
- ArgumentNullException
Thrown when
transformis null.- ArgumentException
Thrown when
destinationis too small to hold the transformed output. A safe minimum size isinput.Length + transform.OutputBlockSize.- InvalidOperationException
Thrown when the transform has been disposed or is in an invalid state.
TransformAsync(ICryptoTransform, Stream, Stream, int, CancellationToken)
Asynchronously applies a cryptographic transformation to data read from a source stream and writes the transformed output to a target stream.
public static Task TransformAsync(this ICryptoTransform transform, Stream sourceStream, Stream targetStream, int bufferSize, CancellationToken cancellationToken = default)
Parameters
transformICryptoTransformThe cryptographic transform to apply. Must not be null.
sourceStreamStreamThe stream to read untransformed data from. Must not be null.
targetStreamStreamThe stream to write transformed data to. Must not be null.
bufferSizeintThe buffer size, in bytes, used for streaming. Must be greater than zero.
cancellationTokenCancellationTokenA token that may be used to cancel the operation before or during processing, including prior to finalization.
Returns
Examples
using var aes = Aes.Create();
using var input = File.OpenRead("input.bin");
using var output = File.Create("encrypted.bin");
await aes.CreateEncryptor().TransformAsync(input, output, 81920);
Remarks
Cancellation is checked before the final block is flushed. If cancellation is requested after the last
successful read but before finalization, an OperationCanceledException is thrown and finalization
is skipped, leaving targetStream in a partial state.
Neither sourceStream nor targetStream is disposed by this method.
Exceptions
- ArgumentNullException
Thrown when
transform,sourceStream, ortargetStreamis null.- ArgumentOutOfRangeException
Thrown when
bufferSizeis less than or equal to zero.- OperationCanceledException
Thrown when the operation is canceled via
cancellationToken.- TaskCanceledException
Thrown when the operation is canceled via the supplied cancellation token.
TransformAsync(ICryptoTransform, ReadOnlyMemory<byte>, Memory<byte>, CancellationToken)
Asynchronously applies a cryptographic transformation to a memory region and writes the transformed result into a destination memory region.
public static Task<int> TransformAsync(this ICryptoTransform transform, ReadOnlyMemory<byte> input, Memory<byte> destination, CancellationToken cancellationToken = default)
Parameters
transformICryptoTransformThe cryptographic transform to apply. Must not be null.
inputReadOnlyMemory<byte>The memory region containing the input data.
destinationMemory<byte>The memory region to receive the transformed output.
cancellationTokenCancellationTokenA token that may be used to cancel the operation before finalization.
Returns
- Task<int>
A Task<TResult> whose result is the number of bytes written to
destination.
Examples
using var aes = Aes.Create();
using var encryptor = aes.CreateEncryptor();
byte[] input = { 0x01, 0x02, 0x03 };
byte[] buffer = new byte[64];
int written = await encryptor.TransformAsync(input, buffer);
Remarks
Cancellation is checked before finalization. If cancellation is requested, an
OperationCanceledException is thrown and the content of destination is
undefined.
Exceptions
- ArgumentNullException
Thrown when
transformis null.- ArgumentException
Thrown when
destinationis too small to hold the transformed output. A safe minimum size isinput.Length + transform.OutputBlockSize.- OperationCanceledException
Thrown when the operation is canceled via
cancellationToken.- InvalidOperationException
Thrown if the internal transformed data buffer cannot be accessed after finalization.
TransformBlock(ICryptoTransform, byte[])
Applies the transform to the entire input buffer, writing the result back into the same array.
public static int TransformBlock(this ICryptoTransform cryptoTransform, byte[] array)
Parameters
cryptoTransformICryptoTransformThe cryptographic transform to apply. Must not be null.
arraybyte[]The input byte array to transform in-place. Must not be null.
Returns
- int
The number of bytes written into
array.
Examples
using var aes = Aes.Create();
byte[] block = GetNextBlock(); // must be block-size aligned
int written = aes.CreateEncryptor().TransformBlock(block);
Remarks
This overload is a convenience wrapper over TransformBlock(byte[], int, int, byte[], int) that reads and writes to the same buffer. The input length must satisfy the block-alignment requirements of the underlying transform.
Exceptions
- ArgumentNullException
Thrown when
cryptoTransformorarrayis null.- ArgumentException
Thrown when the length of
arrayis not a multiple of the transform's InputBlockSize.
TransformFinalBlock(ICryptoTransform)
Finalizes the transformation without processing any additional input data.
public static byte[] TransformFinalBlock(this ICryptoTransform cryptoTransform)
Parameters
cryptoTransformICryptoTransformThe cryptographic transform to finalize. Must not be null.
Returns
- byte[]
A new byte array containing the final block output, which may be empty or contain padding bytes depending on the transform.
Remarks
Use this overload when the transform should be finalized without processing any remaining data.
Exceptions
- ArgumentNullException
Thrown when
cryptoTransformis null.
TransformFinalBlock(ICryptoTransform, byte[])
Finalizes the transformation of the entire specified byte array.
public static byte[] TransformFinalBlock(this ICryptoTransform cryptoTransform, byte[] array)
Parameters
cryptoTransformICryptoTransformThe cryptographic transform to finalize. Must not be null.
arraybyte[]The input array to transform. Must not be null.
Returns
- byte[]
A new byte array containing the final transformed output.
Examples
using var aes = Aes.Create();
byte[] result = aes.CreateEncryptor().TransformFinalBlock(data);
Exceptions
- ArgumentNullException
Thrown when
cryptoTransformorarrayis null.
TransformFinalBlock(ICryptoTransform, byte[], int)
Finalizes the transformation of the specified byte array beginning at the given offset.
public static byte[] TransformFinalBlock(this ICryptoTransform cryptoTransform, byte[] array, int offset)
Parameters
cryptoTransformICryptoTransformThe cryptographic transform to finalize. Must not be null.
arraybyte[]The input array to transform. Must not be null.
offsetintThe zero-based byte offset in
arrayat which to begin reading.
Returns
- byte[]
A new byte array containing the final transformed output.
Exceptions
- ArgumentNullException
Thrown when
cryptoTransformorarrayis null.- ArgumentOutOfRangeException
Thrown when
offsetis negative or exceeds the length ofarray.
TransformFinalBlock(ICryptoTransform, ReadOnlyMemory<byte>)
Finalizes the transformation of the specified memory region.
public static byte[] TransformFinalBlock(this ICryptoTransform cryptoTransform, ReadOnlyMemory<byte> input)
Parameters
cryptoTransformICryptoTransformThe cryptographic transform to finalize. Must not be null.
inputReadOnlyMemory<byte>The input memory region to transform.
Returns
- byte[]
A new byte array containing the final transformed output.
Remarks
This overload delegates to TransformFinalBlock(ICryptoTransform, ReadOnlySpan<byte>).
Exceptions
- ArgumentNullException
Thrown when
cryptoTransformis null.
TransformFinalBlock(ICryptoTransform, ReadOnlySpan<byte>)
Finalizes the transformation of the specified input span.
public static byte[] TransformFinalBlock(this ICryptoTransform cryptoTransform, ReadOnlySpan<byte> input)
Parameters
cryptoTransformICryptoTransformThe cryptographic transform to finalize. Must not be null.
inputReadOnlySpan<byte>The input span of bytes to transform.
Returns
- byte[]
A new byte array containing the final transformed output.
Examples
using var aes = Aes.Create();
byte[] result = aes.CreateEncryptor().TransformFinalBlock(data.AsSpan());
Remarks
This overload writes the input through a CryptoStream and finalizes the block. It avoids array copies for the input data while still producing a new byte array as output.
Exceptions
- ArgumentNullException
Thrown when
cryptoTransformis null.
Applies to
| Product | Versions |
|---|---|
| .NET | 8, 10 |