Repository navigation
OnixLabs.Security.Cryptography.Secret
Represents a cryptographic secret.
| Namespace | OnixLabs.Security.Cryptography |
| Assembly | OnixLabs.Security.Cryptography.dll (NuGet) |
| Inheritance |
object → ValueType → Secret
|
| Implements |
ICryptoPrimitive<Secret>, IValueEquatable<Secret>, IEquatable<Secret>, IBinaryConvertible, ISpanParsable<Secret>, IDisposable
|
public readonly partial struct Secret :
ICryptoPrimitive<Secret>,
ISpanParsable<Secret>,
IDisposableSecret wraps sensitive byte data — such as a password, key material, or private token — and protects it in memory using OS-level data protection (System.Security.Cryptography.ProtectedData). The plaintext bytes are never stored directly; they are encrypted on construction and decrypted on demand via CopyTo(Span<byte>), AsReadOnlySpan() and AsReadOnlyMemory(). The temporary copy made by each constructor is zeroed as soon as it has been encrypted.
Keeping plaintext off the heap
AsReadOnlySpan() and AsReadOnlyMemory() decrypt the secret into a new array on every call. That array stays on the heap until the garbage collector reclaims it, and it cannot be zeroed through the returned span or memory. When the plaintext must not linger, use CopyTo(Span<byte>) to decrypt into a buffer you own, sized by Length, and zero it with CryptographicOperations.ZeroMemory when you are done. The ToString overloads follow the same pattern internally: they decrypt into a temporary buffer (on the stack for secrets of up to 256 bytes) and zero it after formatting.
In addition to encryption, a SHA-256 hash of the original bytes is computed on construction and stored as a Hash. This hash is used for equality comparisons, allowing two Secret values to be compared without exposing the underlying plaintext.
Disposability and copy semantics
Because Secret is a struct, copying the value (e.g., passing by value or assigning to another variable) produces a shallow copy that shares the same underlying ProtectedData instance. Calling Dispose() on any copy zeroes and frees that shared instance, invalidating all copies simultaneously. To avoid surprises, treat a Secret like a reference resource: keep a single owner, use using, and avoid passing by value once construction is complete.
Implicit conversions
Secret exposes six implicit conversion operators covering both byte and char source types, each in ReadOnlySpan<T>, ReadOnlyMemory<T>, and ReadOnlySequence<T> forms. The char-based conversions encode the characters using UTF-8 before protecting them.
Parsing
Secret implements ISpanParsable<Secret>, allowing a hex-encoded (or otherwise base-encoded) string to be decoded back into a Secret. When no IFormatProvider is supplied, Base16FormatProvider.Invariant is used.
Equality
Two Secret values are equal when their SHA-256 hashes are equal, which implies their underlying plaintext bytes were identical at construction time. Equality is thus safe to evaluate even after the secret has been disposed — the hash was computed before the bytes were encrypted.
Warning Avoid storing
Secretin collections, fields, oroutparameters as a value type. Alwaysusing-scope or explicitlyDispose()the owner instance when the secret material is no longer needed.
using OnixLabs.Security.Cryptography;
using Secret secret = new Secret("p@ssw0rd"u8);
// The plaintext is protected in memory; access is via decryption on demand.
ReadOnlySpan<byte> plaintext = secret.AsReadOnlySpan();
Console.WriteLine(secret); // lowercase hex of the UTF-8 bytesusing OnixLabs.Security.Cryptography;
Secret secret = (ReadOnlySpan<char>)"my-api-key";
// Bytes are UTF-8-encoded then immediately protected.using OnixLabs.Security.Cryptography;
Secret parsed = Secret.Parse("deadbeef");
Console.WriteLine(parsed); // deadbeefusing OnixLabs.Security.Cryptography;
using Secret a = new Secret("hunter2"u8);
using Secret b = new Secret("hunter2"u8);
Console.WriteLine(a == b); // True (SHA-256 hashes match)| Constructor | Description |
|---|---|
Secret(ReadOnlySpan<byte>) |
Initializes a new instance from a ReadOnlySpan<byte>. |
Secret(ReadOnlyMemory<byte>) |
Initializes a new instance from a ReadOnlyMemory<byte>. |
Secret(ReadOnlySequence<byte>) |
Initializes a new instance from a ReadOnlySequence<byte>. |
public Secret(ReadOnlySpan<byte> value)Initializes a new instance of the Secret struct. The bytes are immediately protected using ProtectedData and a SHA-256 hash of the plaintext is computed and stored.
| Parameter | Type | Description |
|---|---|---|
value |
ReadOnlySpan<byte> |
The byte span containing the secret material. |
Exceptions
| Exception | Condition |
|---|---|
CryptographicException |
The SHA-256 hash of the secret value could not be computed. |
public Secret(ReadOnlyMemory<byte> value)Initializes a new instance of the Secret struct from a ReadOnlyMemory<byte>.
| Parameter | Type | Description |
|---|---|---|
value |
ReadOnlyMemory<byte> |
The byte memory containing the secret material. |
Exceptions
| Exception | Condition |
|---|---|
CryptographicException |
The SHA-256 hash of the secret value could not be computed. |
public Secret(ReadOnlySequence<byte> value)Initializes a new instance of the Secret struct from a ReadOnlySequence<byte>.
| Parameter | Type | Description |
|---|---|---|
value |
ReadOnlySequence<byte> |
The byte sequence containing the secret material. |
Exceptions
| Exception | Condition |
|---|---|
CryptographicException |
The SHA-256 hash of the secret value could not be computed. |
| Property | Type | Description |
|---|---|---|
Length |
int |
Gets the length of the secret value, in bytes. |
public int Length { get; }Gets the length of the secret value, in bytes, or zero for a default Secret. Use it to size the buffer passed to CopyTo(Span<byte>). Reading Length does not decrypt the secret.
| Method | Returns | Description |
|---|---|---|
Parse(string, IFormatProvider?) |
Secret |
Parses a base-encoded string into a Secret. |
Parse(ReadOnlySpan<char>, IFormatProvider?) |
Secret |
Parses a base-encoded character span into a Secret. |
TryParse(string?, IFormatProvider?, out Secret) |
bool |
Tries to parse a base-encoded string into a Secret. |
TryParse(ReadOnlySpan<char>, IFormatProvider?, out Secret) |
bool |
Tries to parse a base-encoded character span into a Secret. |
public static Secret Parse(string value, IFormatProvider? provider = null)Parses a base-encoded string into a Secret. When provider is null, Base16FormatProvider.Invariant (lowercase hex) is used.
| Parameter | Type | Description |
|---|---|---|
value |
string |
The base-encoded string to parse. |
provider |
IFormatProvider? |
The format provider that selects the base encoding, or null to use Base16FormatProvider.Invariant. |
Returns — A new Secret constructed from the decoded bytes.
Exceptions
| Exception | Condition |
|---|---|
FormatException |
value is not valid for the specified encoding. |
public static Secret Parse(ReadOnlySpan<char> value, IFormatProvider? provider = null)Parses a base-encoded character span into a Secret. When provider is null, Base16FormatProvider.Invariant is used.
| Parameter | Type | Description |
|---|---|---|
value |
ReadOnlySpan<char> |
The base-encoded character span to parse. |
provider |
IFormatProvider? |
The format provider that selects the base encoding, or null to use Base16FormatProvider.Invariant. |
Returns — A new Secret constructed from the decoded bytes.
Exceptions
| Exception | Condition |
|---|---|
FormatException |
value is not valid for the specified encoding. |
public static bool TryParse(string? value, IFormatProvider? provider, out Secret result)Tries to parse a base-encoded string into a Secret. When provider is null, Base16FormatProvider.Invariant is used.
| Parameter | Type | Description |
|---|---|---|
value |
string? |
The base-encoded string to parse. |
provider |
IFormatProvider? |
The format provider that selects the base encoding, or null to use Base16FormatProvider.Invariant. |
result |
out Secret |
On return, contains the parsed value, or default if parsing failed. |
Returns — true if parsing succeeded; otherwise, false.
public static bool TryParse(ReadOnlySpan<char> value, IFormatProvider? provider, out Secret result)Tries to parse a base-encoded character span into a Secret. When provider is null, Base16FormatProvider.Invariant is used.
| Parameter | Type | Description |
|---|---|---|
value |
ReadOnlySpan<char> |
The base-encoded character span to parse. |
provider |
IFormatProvider? |
The format provider that selects the base encoding, or null to use Base16FormatProvider.Invariant. |
result |
out Secret |
On return, contains the parsed value, or default if parsing failed. |
Returns — true if parsing succeeded; otherwise, false.
| Method | Returns | Description |
|---|---|---|
AsReadOnlyMemory() |
ReadOnlyMemory<byte> |
Decrypts and returns the underlying bytes as a ReadOnlyMemory<byte>. |
AsReadOnlySpan() |
ReadOnlySpan<byte> |
Decrypts and returns the underlying bytes as a ReadOnlySpan<byte>. |
CopyTo(Span<byte>) |
void |
Decrypts the underlying bytes into the specified buffer, without placing plaintext on the heap. |
Dispose() |
void |
Zeros and frees the protected key material from memory. |
Equals(Secret) |
bool |
Determines whether this instance equals another Secret by comparing their SHA-256 hashes. |
Equals(object?) |
bool |
Determines whether this instance equals another object. |
GetHashCode() |
int |
Returns a hash code derived from the stored SHA-256 hash. |
ToString() |
string |
Returns the underlying bytes encoded as lowercase hexadecimal. |
ToString(IFormatProvider) |
string |
Returns the underlying bytes encoded using the specified format provider. |
ToString(Encoding) |
string |
Decodes the underlying bytes using the specified text encoding. |
public ReadOnlyMemory<byte> AsReadOnlyMemory()Decrypts the protected data and returns the plaintext bytes as a ReadOnlyMemory<byte>. Returns ReadOnlyMemory<byte>.Empty if the instance has been disposed. Satisfies IBinaryConvertible.
Each call decrypts the secret into a new array, which stays on the heap until it is collected and cannot be zeroed through the returned value. To keep plaintext off the heap, use CopyTo(Span<byte>) with a buffer you zero after use.
Returns — A ReadOnlyMemory<byte> containing the decrypted secret bytes, or empty if disposed.
Exceptions
| Exception | Condition |
|---|---|
ObjectDisposedException |
The underlying ProtectedData has been disposed. |
public ReadOnlySpan<byte> AsReadOnlySpan()Decrypts the protected data and returns the plaintext bytes as a ReadOnlySpan<byte>. Returns ReadOnlySpan<byte>.Empty if the instance has been disposed. Satisfies IBinaryConvertible.
Each call decrypts the secret into a new array, which stays on the heap until it is collected and cannot be zeroed through the returned value. To keep plaintext off the heap, use CopyTo(Span<byte>) with a buffer you zero after use.
Returns — A ReadOnlySpan<byte> over the decrypted secret bytes, or empty if disposed.
Exceptions
| Exception | Condition |
|---|---|
ObjectDisposedException |
The underlying ProtectedData has been disposed. |
public void CopyTo(Span<byte> destination)Copies the decrypted secret value into the specified destination, without placing plaintext on the heap. Only the first Length bytes of destination are written. Unlike AsReadOnlySpan() and AsReadOnlyMemory(), the plaintext exists only in destination; zero it with CryptographicOperations.ZeroMemory when done.
| Parameter | Type | Description |
|---|---|---|
destination |
Span<byte> |
The buffer that receives the secret value, which must be at least Length bytes long. |
Exceptions
| Exception | Condition |
|---|---|
ObjectDisposedException |
The underlying ProtectedData has been disposed. |
ArgumentException |
destination is shorter than Length. |
using System.Security.Cryptography;
using OnixLabs.Security.Cryptography;
using Secret secret = new Secret("p@ssw0rd"u8);
Span<byte> plaintext = stackalloc byte[secret.Length];
try
{
secret.CopyTo(plaintext);
// Use plaintext...
}
finally
{
CryptographicOperations.ZeroMemory(plaintext);
}public void Dispose()Zeros and releases the OS-level protected memory holding the encrypted secret bytes. Because Secret is a struct, all copies share the same ProtectedData instance; disposing one copy invalidates all copies.
public bool Equals(Secret other)Determines whether this instance is equal to other. Equality is determined by comparing the stored SHA-256 hashes of the two secrets; the plaintext bytes are never decrypted for this comparison.
| Parameter | Type | Description |
|---|---|---|
other |
Secret |
The value to compare with this instance. |
Returns — true if the underlying plaintext bytes were identical at construction time; otherwise, false.
public override bool Equals(object? obj)Determines whether this instance is equal to another object.
| Parameter | Type | Description |
|---|---|---|
obj |
object? |
The object to compare with this instance. |
Returns — true if obj is a Secret whose SHA-256 hash matches this instance; otherwise, false.
public override int GetHashCode()Returns a hash code derived from the stored SHA-256 hash of the underlying secret bytes. The secret is not decrypted. Like HashCode, the result is randomised per process and must not be persisted.
Returns — A 32-bit signed integer hash code.
public override string ToString()Returns the underlying bytes encoded as lowercase hexadecimal using Base16FormatProvider.Invariant. The bytes are decrypted on demand.
Returns — A lowercase hexadecimal string representation of the secret bytes.
Exceptions
| Exception | Condition |
|---|---|
ObjectDisposedException |
The underlying ProtectedData has been disposed. |
public string ToString(IFormatProvider provider)Returns the underlying bytes encoded using the specified format provider. Satisfies ICryptoPrimitive<Secret>.
| Parameter | Type | Description |
|---|---|---|
provider |
IFormatProvider |
The format provider that selects the base encoding. |
Returns — A base-encoded string representation of the secret bytes.
Exceptions
| Exception | Condition |
|---|---|
ObjectDisposedException |
The underlying ProtectedData has been disposed. |
public string ToString(Encoding encoding)Decodes the underlying bytes as a text string using the specified Encoding. Use this overload when the secret was originally constructed from character data (e.g., a UTF-8-encoded password).
| Parameter | Type | Description |
|---|---|---|
encoding |
Encoding |
The text encoding used to interpret the underlying bytes. |
Returns — A string decoded from the secret bytes using encoding.
Exceptions
| Exception | Condition |
|---|---|
ObjectDisposedException |
The underlying ProtectedData has been disposed. |
| Operator | Description |
|---|---|
implicit operator Secret(ReadOnlySpan<byte>) |
Creates a Secret from a ReadOnlySpan<byte>. |
implicit operator Secret(ReadOnlyMemory<byte>) |
Creates a Secret from a ReadOnlyMemory<byte>. |
implicit operator Secret(ReadOnlySequence<byte>) |
Creates a Secret from a ReadOnlySequence<byte>. |
implicit operator Secret(ReadOnlySpan<char>) |
Creates a Secret from a UTF-8-encoded ReadOnlySpan<char>. |
implicit operator Secret(ReadOnlyMemory<char>) |
Creates a Secret from a UTF-8-encoded ReadOnlyMemory<char>. |
implicit operator Secret(ReadOnlySequence<char>) |
Creates a Secret from a UTF-8-encoded ReadOnlySequence<char>. |
public static implicit operator Secret(ReadOnlySpan<byte> value)Creates a new Secret from the specified ReadOnlySpan<byte>.
public static implicit operator Secret(ReadOnlyMemory<byte> value)Creates a new Secret from the specified ReadOnlyMemory<byte>.
public static implicit operator Secret(ReadOnlySequence<byte> value)Creates a new Secret from the specified ReadOnlySequence<byte>.
public static implicit operator Secret(ReadOnlySpan<char> value)Creates a new Secret from the specified ReadOnlySpan<char>. The characters are encoded as UTF-8 bytes before the secret is protected.
public static implicit operator Secret(ReadOnlyMemory<char> value)Creates a new Secret from the specified ReadOnlyMemory<char>. The characters are encoded as UTF-8 bytes before the secret is protected.
public static implicit operator Secret(ReadOnlySequence<char> value)Creates a new Secret from the specified ReadOnlySequence<char>. The characters are encoded as UTF-8 bytes before the secret is protected.
| Operator | Description |
|---|---|
operator == |
Determines whether two Secret values are equal. |
operator != |
Determines whether two Secret values are not equal. |
public static bool operator ==(Secret left, Secret right)Determines whether two Secret values are equal by comparing their SHA-256 hashes.
public static bool operator !=(Secret left, Secret right)Determines whether two Secret values are not equal. Returns true if left is not equal to right; otherwise, false.
ONIXLabs .NET Library · Repository · NuGet · License (Apache-2.0)
Copyright © ONIXLabs 2020. Licensed under the Apache License, Version 2.0.
- Enumeration<T>
- Optional<T>
- OptionalEqualityComparer<T>
- OptionalExtensions
- Result
- Result<T>
- ResultEqualityComparer<T>
- ResultExtensions
- Specification<T>
- Preconditions
- IValueEquatable<T>
- IValueComparable<T>
- IBinaryConvertible
- ISpanBinaryConvertible
- IMemoryBinaryConvertible
- ArrayExtensions
- ComparableExtensions
- DateTimeExtensions
- ISpanParsableExtensions
- ObjectExtensions
- RandomExtensions
- ReadOnlySequenceExtensions
- ReadOnlySpanExtensions
- StringExtensions
- Base16
- Base32
- Base58
- Base64
- IBaseCodec
- IBaseValue
- IBaseValue<T>
- Base16Codec
- Base32Codec
- Base58Codec
- Base64Codec
- Base16FormatProvider
- Base32FormatProvider
- Base58FormatProvider
- Base64FormatProvider
- EncodingExtensions
- ReadOnlySpanExtensions
- StringBuilderExtensions
- BigDecimal
- BigDecimalEqualityComparer
- BigDecimalOrdinalityComparer
- NumberInfo
- NumberInfoEqualityComparer
- NumberInfoOrdinalityComparer
- Int256
- Int512
- UInt256
- UInt512
- Float128
- Float256
- GenericMath
- NumericsExtensions
- ConversionMode
- ScaleMode
- Hash
- NamedHash
- Sha3
- Sha3Hash224
- Sha3Hash256
- Sha3Hash384
- Sha3Hash512
- Sha3Shake128
- Sha3Shake256
- MerkleTree
- MerkleTree<T>
- PrivateKey
- PublicKey
- NamedPrivateKey
- NamedPublicKey
- EcdhPrivateKey
- EcdhPublicKey
- EcdsaPrivateKey
- EcdsaPublicKey
- EddsaPrivateKey
- EddsaPublicKey
- RsaPrivateKey
- RsaPublicKey
- DigitalSignature
- DigitalSignatureAndPublicKey
- Salt
- Secret
- ICryptoPrimitive<T>
- IHashable
- IEcdhPrivateKey
- IEcdsaPrivateKey
- IEddsaPrivateKey
- IRsaPrivateKey
- IPrivateKeyDerivable<T>
- IPrivateKeyExportable
- IPrivateKeyImportable<T>
- IPrivateKeyPemImportable<T>
- IPrivateKeyPkcs8Exportable
- IPrivateKeyPkcs8Importable<T>
- IPrivateKeyPkcs8PemExportable
- IPrivateKeyRawExportable
- IPrivateKeyRawImportable<T>
- IPrivateKeyRawPemExportable
- IEcdhPublicKey
- IEcdsaPublicKey
- IEddsaPublicKey
- IRsaPublicKey
- IPublicKeyExportable
- IPublicKeyImportable<T>
- IPublicKeyPemExportable
- IPublicKeyPemImportable<T>
- IPublicKeyRawExportable
- IPublicKeyRawImportable<T>
- HashAlgorithmExtensions
- ReadOnlySpanExtensions