Class ScyllaCrypto
Provides authenticated encryption and decryption operations for the Scylla framework. Supports three algorithms - AESGCM (recommended), AESCBCHMAC, and CHACHA20POLY1305 - across two modes: password-based (with PBKDF2 key derivation) and key-based (pre-derived key supplied by caller).
Inherited Members
Namespace: Scylla.Core.Util.Crypto
Assembly: ScyllaCore.dll
Syntax
public static class ScyllaCrypto
Remarks
Encryption modes
Password-based encryption (Encrypt(byte[], string), EncryptAsync(byte[], string, CancellationToken), EncryptString(string, string)) generates a random salt, runs PBKDF2 to derive a key, and embeds all parameters needed for decryption directly in the output. The caller only needs the original password to decrypt - no salt or iteration count need to be stored separately.
Key-based encryption (EncryptWithKey(byte[], byte[]), EncryptWithKeyAsync(byte[], byte[], CancellationToken)) accepts a raw 16-, 24-, or 32-byte key and skips key derivation entirely, making it significantly faster. The caller is responsible for managing the key securely.
Self-describing binary format
Every ciphertext produced by this class includes a compact header so decryption is fully
self-contained. The password-based header is 9 bytes:
[Version(1)] [Algorithm(1)] [KeySizeBits(2)] [Iterations(4)] [SaltSize(1)],
followed by the salt and then the algorithm-specific ciphertext payload.
The key-based header is 3 bytes:
[Version(1)] [Algorithm(1)] [KeySizeBytes(1)],
followed immediately by the payload. The algorithm byte always records which algorithm was
actually used after any automatic fallback, not which was requested.
Algorithm auto-fallback
When AESGCM is requested but the platform does not support it (e.g., WebGL), the class automatically falls back to AESCBCHMAC and records the fallback algorithm in the ciphertext header. CHACHA20POLY1305 is an explicit opt-in and has no automatic fallback - if ChaCha20 is unavailable a CryptoException with UnsupportedAlgorithm is thrown. Use IsAlgorithmSupported(CryptoAlgorithm) or GetBestAvailableAlgorithm() to check availability before committing to a specific algorithm.
Default algorithm
DefaultAlgorithm is set at startup to GetBestAvailableAlgorithm(), so on most platforms it will be AESGCM. You can override it globally by setting DefaultAlgorithm before performing any operations, or per-call by supplying a CryptoSettings instance with a specific Algorithm value.
Thread safety
All static methods on this class are thread-safe. The three static configuration properties (DefaultAlgorithm, DefaultKeySize, DefaultIterations) are plain properties without synchronization - set them once during application startup before spawning threads that call encryption methods.
Secure memory handling
All internally allocated key and salt buffers are zeroed via SecureClear(byte[]) in
finally blocks, minimizing the window during which sensitive material lives in the
managed heap. Caller-supplied plaintext and key arrays are never modified.
Properties
DefaultAlgorithm
Gets or sets the default encryption algorithm used when no CryptoSettings is supplied to an encryption method.
Declaration
public static CryptoAlgorithm DefaultAlgorithm { get; set; }
Property Value
| Type | Description |
|---|---|
| CryptoAlgorithm |
Remarks
Initialized at startup via GetBestAvailableAlgorithm(): resolves to AESGCM on platforms that support it, and falls back to AESCBCHMAC (e.g., WebGL) otherwise. Override this property once during application startup to enforce a specific algorithm globally. Per-call overrides are always possible by supplying a CryptoSettings instance with a specific Algorithm value.
DefaultIterations
Gets or sets the default PBKDF2 iteration count applied during password-based encryption when no CryptoSettings is supplied. Defaults to DEFAULT_ITERATIONS (600,000).
Declaration
public static int DefaultIterations { get; set; }
Property Value
| Type | Description |
|---|---|
| int |
Remarks
Higher iteration counts increase resistance to offline brute-force attacks at the cost of longer key derivation time. The value is embedded in the ciphertext header and used automatically during decryption, so encryption and decryption do not need to agree on this value ahead of time. Minimum allowed value is MIN_ITERATIONS (10,000); values below that threshold are rejected by Validate().
DefaultKeySize
Gets or sets the default AES key size in bits used when no CryptoSettings is supplied. Valid values are 128, 192, or 256. Defaults to 256.
Declaration
public static int DefaultKeySize { get; set; }
Property Value
| Type | Description |
|---|---|
| int |
Remarks
Note that CHACHA20POLY1305 always uses 256-bit keys regardless of this setting. For AES-based algorithms, 256-bit keys are recommended for maximum security; 128-bit keys offer a good balance of performance and security for less sensitive data.
Methods
ConstantTimeEquals(byte[], byte[])
Compares two byte arrays for equality in constant time, regardless of their content, to prevent timing-based side-channel attacks that could leak information about the expected value by measuring how long comparison takes.
Declaration
public static bool ConstantTimeEquals(byte[] a, byte[] b)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | a | The first byte array. May be |
| byte[] | b | The second byte array. May be |
Returns
| Type | Description |
|---|---|
| bool |
|
Remarks
Unlike a standard equality comparison that short-circuits on the first mismatch, this method always examines every byte before returning, ensuring that attack tooling cannot determine how many prefix bytes match. Use this whenever comparing authentication tags, HMAC values, or other security-sensitive byte sequences.
Decrypt(byte[], string)
Decrypts a byte array that was produced by Encrypt(byte[], string) or Encrypt(byte[], string, CryptoSettings), recovering the original plaintext.
Declaration
public static byte[] Decrypt(byte[] ciphertext, string password)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | ciphertext | The encrypted data as returned by an |
| string | password | The password that was used during encryption. Must not be |
Returns
| Type | Description |
|---|---|
| byte[] | The decrypted plaintext bytes. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
Decrypt(byte[], string, CryptoSettings)
Decrypts a byte array that was produced by an Encrypt overload, recovering the original plaintext.
Algorithm, key size, and salt are read from the embedded ciphertext header; the optional
settings parameter can override the hash algorithm used during re-derivation
but cannot override the algorithm or key size that were recorded at encryption time.
Declaration
public static byte[] Decrypt(byte[] ciphertext, string password, CryptoSettings settings)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | ciphertext | The encrypted data as returned by an |
| string | password | The password that was used during encryption. Must not be |
| CryptoSettings | settings | Optional settings. When non- |
Returns
| Type | Description |
|---|---|
| byte[] | The decrypted plaintext bytes. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
DecryptAsync(byte[], string, CryptoSettings, CancellationToken)
Asynchronously decrypts a byte array that was produced by an Encrypt or EncryptAsync
overload, using the provided CryptoSettings for any derivation parameter overrides,
and offloading key re-derivation to a background thread.
Declaration
public static Task<byte[]> DecryptAsync(byte[] ciphertext, string password, CryptoSettings settings, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | ciphertext | The encrypted data as returned by an |
| string | password | The password that was used during encryption. Must not be |
| CryptoSettings | settings | Optional settings. The Algorithm and
KeySizeBits fields are always overridden by the values embedded
in the ciphertext header. Pass |
| CancellationToken | cancellationToken | Optional token used to cancel the background key derivation operation. |
Returns
| Type | Description |
|---|---|
| Task<byte[]> | A task that resolves to the decrypted plaintext bytes. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
DecryptAsync(byte[], string, CancellationToken)
Asynchronously decrypts a byte array that was produced by an EncryptAsync or Encrypt
overload, offloading CPU-intensive PBKDF2 key re-derivation to a background thread.
Algorithm, key size, iteration count, and salt are all read from the embedded header.
Declaration
public static Task<byte[]> DecryptAsync(byte[] ciphertext, string password, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | ciphertext | The encrypted data as returned by an |
| string | password | The password that was used during encryption. Must not be |
| CancellationToken | cancellationToken | Optional token used to cancel the background key derivation. When cancelled, the returned task faults with a CryptoException carrying OperationCancelled. |
Returns
| Type | Description |
|---|---|
| Task<byte[]> | A task that resolves to the decrypted plaintext bytes. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
DecryptString(string, string)
Decrypts a Base64-encoded ciphertext that was produced by EncryptString(string, string) or EncryptString(string, string, CryptoSettings), returning the original UTF-8 string.
Declaration
public static string DecryptString(string ciphertext, string password)
Parameters
| Type | Name | Description |
|---|---|---|
| string | ciphertext | The Base64-encoded encrypted string as returned by an |
| string | password | The password that was used during encryption. Must not be |
Returns
| Type | Description |
|---|---|
| string | The decrypted string, decoded from UTF-8. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
DecryptString(string, string, CryptoSettings)
Decrypts a Base64-encoded ciphertext that was produced by an EncryptString overload,
returning the original UTF-8 string, using the provided CryptoSettings for
any derivation parameter overrides.
Declaration
public static string DecryptString(string ciphertext, string password, CryptoSettings settings)
Parameters
| Type | Name | Description |
|---|---|---|
| string | ciphertext | The Base64-encoded encrypted string as returned by an |
| string | password | The password that was used during encryption. Must not be |
| CryptoSettings | settings | Optional settings forwarded to Decrypt(byte[], string, CryptoSettings).
Pass |
Returns
| Type | Description |
|---|---|
| string | The decrypted string, decoded from UTF-8. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
DecryptStringAsync(string, string, CryptoSettings, CancellationToken)
Asynchronously decrypts a Base64-encoded ciphertext that was produced by an EncryptString
or EncryptStringAsync overload, using the provided CryptoSettings for any
derivation parameter overrides, and offloading key re-derivation to a background thread.
Declaration
public static Task<string> DecryptStringAsync(string ciphertext, string password, CryptoSettings settings, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| string | ciphertext | The Base64-encoded encrypted string as returned by an |
| string | password | The password that was used during encryption. Must not be |
| CryptoSettings | settings | Optional settings forwarded to DecryptAsync(byte[], string, CryptoSettings, CancellationToken).
Pass |
| CancellationToken | cancellationToken | Optional token used to cancel the background key derivation. |
Returns
| Type | Description |
|---|---|
| Task<string> | A task that resolves to the decrypted string, decoded from UTF-8. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
DecryptStringAsync(string, string, CancellationToken)
Asynchronously decrypts a Base64-encoded ciphertext that was produced by an
EncryptString or EncryptStringAsync overload, returning the original UTF-8 string.
Offloads PBKDF2 key re-derivation to a background thread.
Declaration
public static Task<string> DecryptStringAsync(string ciphertext, string password, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| string | ciphertext | The Base64-encoded encrypted string as returned by an |
| string | password | The password that was used during encryption. Must not be |
| CancellationToken | cancellationToken | Optional token used to cancel the background key derivation. |
Returns
| Type | Description |
|---|---|
| Task<string> | A task that resolves to the decrypted string, decoded from UTF-8. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
DecryptWithKey(byte[], byte[])
Decrypts a byte array that was produced by EncryptWithKey(byte[], byte[]) or EncryptWithKey(byte[], byte[], CryptoSettings), recovering the original plaintext. The algorithm and key size are read directly from the embedded 3-byte header.
Declaration
public static byte[] DecryptWithKey(byte[] ciphertext, byte[] key)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | ciphertext | The encrypted data as returned by an |
| byte[] | key | The same key that was supplied during encryption. Must not be |
Returns
| Type | Description |
|---|---|
| byte[] | The decrypted plaintext bytes. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
DecryptWithKey(byte[], byte[], CryptoSettings)
Decrypts a byte array that was produced by an EncryptWithKey overload, recovering the
original plaintext. The algorithm and key size are always read from the embedded header;
settings is accepted for API symmetry but currently has no effect on
key-based decryption beyond what is recorded in the header.
Declaration
public static byte[] DecryptWithKey(byte[] ciphertext, byte[] key, CryptoSettings settings)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | ciphertext | The encrypted data as returned by an |
| byte[] | key | The same key that was supplied during encryption. Must not be |
| CryptoSettings | settings | Optional settings. Currently unused for key-based decryption - the algorithm and key size
are determined entirely from the ciphertext header. Pass |
Returns
| Type | Description |
|---|---|
| byte[] | The decrypted plaintext bytes. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
DecryptWithKeyAsync(byte[], byte[], CryptoSettings, CancellationToken)
Asynchronously decrypts a byte array that was produced by an EncryptWithKey or
EncryptWithKeyAsync overload, using the provided CryptoSettings (currently
unused for key-based decryption; algorithm and key size are always read from the header).
Declaration
public static Task<byte[]> DecryptWithKeyAsync(byte[] ciphertext, byte[] key, CryptoSettings settings, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | ciphertext | The encrypted data as returned by an |
| byte[] | key | The same key that was supplied during encryption. Must not be |
| CryptoSettings | settings | Optional settings. Currently unused for key-based decryption. Pass |
| CancellationToken | cancellationToken | Optional token used to cancel the operation. |
Returns
| Type | Description |
|---|---|
| Task<byte[]> | A task that resolves to the decrypted plaintext bytes. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
DecryptWithKeyAsync(byte[], byte[], CancellationToken)
Asynchronously decrypts a byte array that was produced by an EncryptWithKey or
EncryptWithKeyAsync overload, recovering the original plaintext. The algorithm and
key size are read from the embedded 3-byte header.
Declaration
public static Task<byte[]> DecryptWithKeyAsync(byte[] ciphertext, byte[] key, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | ciphertext | The encrypted data as returned by an |
| byte[] | key | The same key that was supplied during encryption. Must not be |
| CancellationToken | cancellationToken | Optional token used to cancel the operation. |
Returns
| Type | Description |
|---|---|
| Task<byte[]> | A task that resolves to the decrypted plaintext bytes. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
DeriveKey(string, byte[], KeyDerivationSettings)
Derives a cryptographic key from a password using PBKDF2 with full control over iteration count, output size, and hash algorithm via a KeyDerivationSettings instance.
Declaration
public static byte[] DeriveKey(string password, byte[] salt, KeyDerivationSettings settings)
Parameters
| Type | Name | Description |
|---|---|---|
| string | password | The password to derive the key from. Must not be |
| byte[] | salt | A cryptographic salt. Must not be |
| KeyDerivationSettings | settings | Key derivation settings controlling iteration count, output key size in bytes, and hash algorithm.
Must not be |
Returns
| Type | Description |
|---|---|
| byte[] | A byte array of the length specified by KeySizeBytes. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with InvalidPassword if |
See Also
DeriveKey(string, byte[], int)
Derives a cryptographic key from a password using PBKDF2 (Password-Based Key Derivation Function 2) with default SHA-256 hashing and 600,000 iterations. Use this when you need to produce a raw key for use with EncryptWithKey(byte[], byte[]) or external APIs, rather than using password-based Encrypt(byte[], string) which handles derivation internally.
Declaration
public static byte[] DeriveKey(string password, byte[] salt, int keySizeBytes = 32)
Parameters
| Type | Name | Description |
|---|---|---|
| string | password | The password to derive the key from. Must not be |
| byte[] | salt | A cryptographic salt. Must not be |
| int | keySizeBytes | The desired output key length in bytes. Defaults to 32 (256-bit key). Typical values: 16 (128-bit), 24 (192-bit), 32 (256-bit). |
Returns
| Type | Description |
|---|---|
| byte[] | A byte array of length |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with InvalidPassword if |
See Also
DeriveKeyAsync(string, byte[], KeyDerivationSettings, CancellationToken)
Asynchronously derives a cryptographic key from a password using PBKDF2 with full control over iteration count, output size, and hash algorithm via a KeyDerivationSettings instance, offloading the CPU-intensive work to a background thread.
Declaration
public static Task<byte[]> DeriveKeyAsync(string password, byte[] salt, KeyDerivationSettings settings, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| string | password | The password to derive the key from. Must not be |
| byte[] | salt | A cryptographic salt. Must not be |
| KeyDerivationSettings | settings | Key derivation settings controlling iteration count, output key size, and hash algorithm. Use Default for standard 600,000-iteration SHA-256 derivation. |
| CancellationToken | cancellationToken | Optional token used to cancel the background derivation. |
Returns
| Type | Description |
|---|---|
| Task<byte[]> | A task that resolves to a byte array of the length specified in |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with InvalidPassword if |
See Also
DeriveKeyAsync(string, byte[], int, CancellationToken)
Asynchronously derives a cryptographic key from a password using PBKDF2 with default SHA-256 hashing and 600,000 iterations, offloading the CPU-intensive work to a background thread. Prefer this over DeriveKey(string, byte[], int) in Unity async methods and coroutines to avoid stalling the main thread for the duration of key derivation.
Declaration
public static Task<byte[]> DeriveKeyAsync(string password, byte[] salt, int keySizeBytes = 32, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| string | password | The password to derive the key from. Must not be |
| byte[] | salt | A cryptographic salt. Must not be |
| int | keySizeBytes | The desired output key length in bytes. Defaults to 32 (256-bit key). |
| CancellationToken | cancellationToken | Optional token used to cancel the background derivation. When cancelled, the returned task faults with a CryptoException carrying OperationCancelled. |
Returns
| Type | Description |
|---|---|
| Task<byte[]> | A task that resolves to a byte array of length |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with InvalidPassword if |
See Also
Encrypt(byte[], string)
Encrypts a byte array using a password with PBKDF2 key derivation and authenticated encryption, applying default algorithm and iteration settings.
Declaration
public static byte[] Encrypt(byte[] plaintext, string password)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | plaintext | The raw bytes to encrypt. Must not be |
| string | password | The password from which the encryption key is derived. Must not be |
Returns
| Type | Description |
|---|---|
| byte[] | A self-describing byte array containing the format header, random salt, and encrypted payload. Pass this directly to Decrypt(byte[], string) to recover the plaintext. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
Encrypt(byte[], string, CryptoSettings)
Encrypts a byte array using a password with PBKDF2 key derivation and authenticated encryption, using the provided CryptoSettings to control algorithm, key size, and iteration count.
Declaration
public static byte[] Encrypt(byte[] plaintext, string password, CryptoSettings settings)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | plaintext | The raw bytes to encrypt. Must not be |
| string | password | The password from which the encryption key is derived. Must not be |
| CryptoSettings | settings | Optional encryption settings controlling algorithm choice, key size, PBKDF2 iteration count,
salt size, and hash algorithm. Pass |
Returns
| Type | Description |
|---|---|
| byte[] | A self-describing byte array containing the format header, random salt, and encrypted payload. Pass this directly to Decrypt(byte[], string, CryptoSettings) to recover the plaintext. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
EncryptAsync(byte[], string, CryptoSettings, CancellationToken)
Asynchronously encrypts a byte array using a password and the provided CryptoSettings, offloading CPU-intensive PBKDF2 key derivation to a background thread.
Declaration
public static Task<byte[]> EncryptAsync(byte[] plaintext, string password, CryptoSettings settings, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | plaintext | The raw bytes to encrypt. Must not be |
| string | password | The password from which the encryption key is derived. Must not be |
| CryptoSettings | settings | Optional encryption settings. Pass |
| CancellationToken | cancellationToken | Optional token used to cancel the background key derivation operation. |
Returns
| Type | Description |
|---|---|
| Task<byte[]> | A task that resolves to the self-describing encrypted byte array, identical in format to the synchronous Encrypt(byte[], string, CryptoSettings) output. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
EncryptAsync(byte[], string, CancellationToken)
Asynchronously encrypts a byte array using a password with PBKDF2 key derivation and authenticated encryption, offloading CPU-intensive key derivation to a background thread to keep the calling thread (e.g., the Unity main thread) responsive.
Declaration
public static Task<byte[]> EncryptAsync(byte[] plaintext, string password, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | plaintext | The raw bytes to encrypt. Must not be |
| string | password | The password from which the encryption key is derived. Must not be |
| CancellationToken | cancellationToken | Optional token used to cancel the background key derivation. When cancelled, the returned task faults with a CryptoException carrying OperationCancelled. |
Returns
| Type | Description |
|---|---|
| Task<byte[]> | A task that resolves to the self-describing encrypted byte array, identical in format to the synchronous Encrypt(byte[], string) output. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
EncryptString(string, string)
Encrypts a UTF-8 string using a password and returns the ciphertext as a Base64-encoded string, using default algorithm settings. This is a convenience wrapper around Encrypt(byte[], string) for working with string data without manually managing byte conversion.
Declaration
public static string EncryptString(string plaintext, string password)
Parameters
| Type | Name | Description |
|---|---|---|
| string | plaintext | The string to encrypt. Must not be |
| string | password | The password from which the encryption key is derived. Must not be |
Returns
| Type | Description |
|---|---|
| string | A Base64-encoded string representing the self-describing ciphertext. This value is safe to store in text files, JSON, or transmit over text-based channels. Pass it directly to DecryptString(string, string) to recover the original string. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
EncryptString(string, string, CryptoSettings)
Encrypts a UTF-8 string using a password and returns the ciphertext as a Base64-encoded string, using the provided CryptoSettings.
Declaration
public static string EncryptString(string plaintext, string password, CryptoSettings settings)
Parameters
| Type | Name | Description |
|---|---|---|
| string | plaintext | The string to encrypt. Must not be |
| string | password | The password from which the encryption key is derived. Must not be |
| CryptoSettings | settings | Optional encryption settings. Pass |
Returns
| Type | Description |
|---|---|
| string | A Base64-encoded string representing the self-describing ciphertext. Pass it directly to DecryptString(string, string, CryptoSettings) to recover the original string. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
EncryptStringAsync(string, string, CryptoSettings, CancellationToken)
Asynchronously encrypts a UTF-8 string using a password and the provided CryptoSettings, offloading CPU-intensive PBKDF2 key derivation to a background thread.
Declaration
public static Task<string> EncryptStringAsync(string plaintext, string password, CryptoSettings settings, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| string | plaintext | The string to encrypt. Must not be |
| string | password | The password from which the encryption key is derived. Must not be |
| CryptoSettings | settings | Optional encryption settings. Pass |
| CancellationToken | cancellationToken | Optional token used to cancel the background key derivation. |
Returns
| Type | Description |
|---|---|
| Task<string> | A task that resolves to a Base64-encoded encrypted string. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
EncryptStringAsync(string, string, CancellationToken)
Asynchronously encrypts a UTF-8 string using a password and returns the ciphertext as a Base64-encoded string, offloading CPU-intensive PBKDF2 key derivation to a background thread. This is the async equivalent of EncryptString(string, string) and is preferred in Unity coroutines and async methods where blocking the main thread is not acceptable.
Declaration
public static Task<string> EncryptStringAsync(string plaintext, string password, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| string | plaintext | The string to encrypt. Must not be |
| string | password | The password from which the encryption key is derived. Must not be |
| CancellationToken | cancellationToken | Optional token used to cancel the background key derivation. |
Returns
| Type | Description |
|---|---|
| Task<string> | A task that resolves to a Base64-encoded encrypted string safe for storage in text formats. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
EncryptWithKey(byte[], byte[])
Encrypts a byte array using a pre-derived raw cryptographic key, applying the default algorithm. Skips PBKDF2 key derivation entirely, making this significantly faster than the password-based overloads when a key is already available (e.g., from GenerateKey(int) or a prior DeriveKey(string, byte[], int) call).
Declaration
public static byte[] EncryptWithKey(byte[] plaintext, byte[] key)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | plaintext | The raw bytes to encrypt. Must not be |
| byte[] | key | The encryption key. Must not be |
Returns
| Type | Description |
|---|---|
| byte[] | A self-describing byte array containing the 3-byte key-based format header and the encrypted payload. Pass this to DecryptWithKey(byte[], byte[]) with the same key to recover the plaintext. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
EncryptWithKey(byte[], byte[], CryptoSettings)
Encrypts a byte array using a pre-derived raw cryptographic key and explicit settings.
The Algorithm field of settings selects
the cipher; key size and iteration count fields are ignored because no key derivation occurs.
Declaration
public static byte[] EncryptWithKey(byte[] plaintext, byte[] key, CryptoSettings settings)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | plaintext | The raw bytes to encrypt. Must not be |
| byte[] | key | The encryption key. Must not be |
| CryptoSettings | settings | Optional settings. Only Algorithm is meaningful here;
pass |
Returns
| Type | Description |
|---|---|
| byte[] | A self-describing byte array containing the 3-byte key-based format header and the encrypted payload. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
EncryptWithKeyAsync(byte[], byte[], CryptoSettings, CancellationToken)
Asynchronously encrypts a byte array using a pre-derived raw cryptographic key and explicit settings.
Declaration
public static Task<byte[]> EncryptWithKeyAsync(byte[] plaintext, byte[] key, CryptoSettings settings, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | plaintext | The raw bytes to encrypt. Must not be |
| byte[] | key | The encryption key. Must not be |
| CryptoSettings | settings | Optional settings. Only Algorithm is meaningful here;
pass |
| CancellationToken | cancellationToken | Optional token used to cancel the operation. |
Returns
| Type | Description |
|---|---|
| Task<byte[]> | A task that resolves to a self-describing encrypted byte array in key-based format. |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
EncryptWithKeyAsync(byte[], byte[], CancellationToken)
Asynchronously encrypts a byte array using a pre-derived raw cryptographic key, applying the default algorithm. Because no key derivation occurs, this method is less CPU-bound than the password-based async overloads; the async overhead comes primarily from the cipher operation itself.
Declaration
public static Task<byte[]> EncryptWithKeyAsync(byte[] plaintext, byte[] key, CancellationToken cancellationToken = default)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | plaintext | The raw bytes to encrypt. Must not be |
| byte[] | key | The encryption key. Must not be |
| CancellationToken | cancellationToken | Optional token used to cancel the operation. When cancelled, the returned task faults with a CryptoException carrying OperationCancelled. |
Returns
| Type | Description |
|---|---|
| Task<byte[]> | A task that resolves to a self-describing encrypted byte array in key-based format, identical to the output of EncryptWithKey(byte[], byte[]). |
Exceptions
| Type | Condition |
|---|---|
| CryptoException | Thrown with NullData if |
See Also
GenerateKey(int)
Generates a cryptographically secure random AES key of a standard size, suitable for use with EncryptWithKey(byte[], byte[]) and DecryptWithKey(byte[], byte[]).
Declaration
public static byte[] GenerateKey(int sizeBytes = 32)
Parameters
| Type | Name | Description |
|---|---|---|
| int | sizeBytes | The desired key length in bytes. Must be exactly 16 (128-bit), 24 (192-bit), or 32 (256-bit). Any other value causes an ArgumentOutOfRangeException. Defaults to 32 (256-bit), which is recommended for maximum security. |
Returns
| Type | Description |
|---|---|
| byte[] | A new byte array of length |
Exceptions
| Type | Condition |
|---|---|
| ArgumentOutOfRangeException | Thrown when |
See Also
GenerateSalt(int)
Generates a cryptographically secure random salt suitable for use with DeriveKey(string, byte[], int) or any PBKDF2-based key derivation. The salt must be stored alongside the encrypted data so that the same key can be re-derived during decryption.
Declaration
public static byte[] GenerateSalt(int sizeBytes = 32)
Parameters
| Type | Name | Description |
|---|---|---|
| int | sizeBytes | The desired salt length in bytes. Defaults to 32 (256 bits), which exceeds the minimum recommended size. Must be at least 16; values below this threshold cause an ArgumentOutOfRangeException. |
Returns
| Type | Description |
|---|---|
| byte[] | A new byte array of length |
Exceptions
| Type | Condition |
|---|---|
| ArgumentOutOfRangeException | Thrown when |
See Also
GetBestAvailableAlgorithm()
Returns the most secure algorithm that is available on the current platform. Prefers AESGCM where hardware-accelerated AEAD is supported; falls back to AESCBCHMAC when AES-GCM is unavailable (e.g., WebGL).
Declaration
public static CryptoAlgorithm GetBestAvailableAlgorithm()
Returns
| Type | Description |
|---|---|
| CryptoAlgorithm | AESGCM if AES-GCM is supported on this platform; otherwise AESCBCHMAC. |
Remarks
This method is called once at class initialization to set DefaultAlgorithm. You can also call it directly at runtime to verify the fallback that will be applied on the current platform before performing any encryption.
See Also
IsAlgorithmSupported(CryptoAlgorithm)
Returns whether the specified CryptoAlgorithm is available on the current platform. Use this to check algorithm availability before committing to a specific algorithm in Algorithm or DefaultAlgorithm.
Declaration
public static bool IsAlgorithmSupported(CryptoAlgorithm algorithm)
Parameters
| Type | Name | Description |
|---|---|---|
| CryptoAlgorithm | algorithm | The algorithm whose platform availability should be checked. |
Returns
| Type | Description |
|---|---|
| bool |
|
Remarks
AESCBCHMAC is always supported on all platforms. AESGCM is unavailable on WebGL. CHACHA20POLY1305 availability depends on the .NET runtime version and platform hardware.
See Also
SecureClear(byte[])
Overwrites every byte in data with zero to reduce the window during which
sensitive key or plaintext material is readable from the managed heap.
Declaration
public static void SecureClear(byte[] data)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | data | The byte array to clear. If |
Remarks
The underlying Clear(Array, int, int) call is decorated with NoOptimization to prevent the JIT from eliding the zeroing as a dead-store optimization. This does not guarantee the data cannot be recovered via memory dumps before this method is called - zero as early as possible.
TryDecrypt(byte[], string, CryptoSettings, out byte[])
Attempts to decrypt a password-encrypted byte array without throwing on failure, using the provided CryptoSettings for any derivation overrides.
Declaration
public static bool TryDecrypt(byte[] ciphertext, string password, CryptoSettings settings, out byte[] plaintext)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | ciphertext | The encrypted data as returned by an |
| string | password | The password that was used during encryption. |
| CryptoSettings | settings | Optional settings forwarded to Decrypt(byte[], string, CryptoSettings).
Pass |
| byte[] | plaintext | When this method returns |
Returns
| Type | Description |
|---|---|
| bool |
|
See Also
TryDecrypt(byte[], string, out byte[])
Attempts to decrypt a password-encrypted byte array without throwing on failure. Use this overload when a decryption failure is a recoverable condition (e.g., verifying multiple candidate passwords) and exception overhead is undesirable.
Declaration
public static bool TryDecrypt(byte[] ciphertext, string password, out byte[] plaintext)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | ciphertext | The encrypted data as returned by an |
| string | password | The password that was used during encryption. |
| byte[] | plaintext | When this method returns |
Returns
| Type | Description |
|---|---|
| bool |
|
See Also
TryDecryptString(string, string, CryptoSettings, out string)
Attempts to decrypt a Base64-encoded encrypted string without throwing on failure, using the provided CryptoSettings for any derivation parameter overrides.
Declaration
public static bool TryDecryptString(string ciphertext, string password, CryptoSettings settings, out string plaintext)
Parameters
| Type | Name | Description |
|---|---|---|
| string | ciphertext | The Base64-encoded encrypted string as returned by an |
| string | password | The password that was used during encryption. |
| CryptoSettings | settings | Optional settings forwarded to DecryptString(string, string, CryptoSettings).
Pass |
| string | plaintext | When this method returns |
Returns
| Type | Description |
|---|---|
| bool |
|
See Also
TryDecryptString(string, string, out string)
Attempts to decrypt a Base64-encoded encrypted string without throwing on failure. Use this overload when a decryption failure is a recoverable condition and exception overhead is undesirable (e.g., checking multiple candidate passwords for a stored secret).
Declaration
public static bool TryDecryptString(string ciphertext, string password, out string plaintext)
Parameters
| Type | Name | Description |
|---|---|---|
| string | ciphertext | The Base64-encoded encrypted string as returned by an |
| string | password | The password that was used during encryption. |
| string | plaintext | When this method returns |
Returns
| Type | Description |
|---|---|
| bool |
|