Skip to content

OnixLabs.Security.Cryptography.PrivateKey

Matthew Layton edited this page Nov 15, 2026 · 3 revisions

PrivateKey Class

Represents the abstract base class for all asymmetric cryptographic private keys. EcdhPrivateKey, EcdsaPrivateKey, EddsaPrivateKey, and RsaPrivateKey all derive from this class.

Namespace OnixLabs.Security.Cryptography
Assembly OnixLabs.Security.Cryptography.dll (NuGet)
Inheritance object → PrivateKey
Implements ICryptoPrimitive<PrivateKey>, IValueEquatable<PrivateKey>, IEquatable<PrivateKey>, IBinaryConvertible, IDisposable
Derived EcdhPrivateKey, EcdsaPrivateKey, EddsaPrivateKey, RsaPrivateKey

Definition

public abstract partial class PrivateKey : ICryptoPrimitive<PrivateKey>, IDisposable

Remarks

PrivateKey is the root of the asymmetric private-key hierarchy. It holds raw key material in memory using an internal ProtectedData wrapper that encrypts the bytes at rest, limiting the window during which clear key bytes are accessible. The key bytes are only decrypted in-process when they are requested (through CopyTo, AsReadOnlySpan, AsReadOnlyMemory, the ToString overloads, or the protected KeyData property), and they are scrubbed when the instance is disposed.

Because the constructor is protected, only subclasses can instantiate PrivateKey. Three overloads accept ReadOnlySpan<byte>, ReadOnlyMemory<byte>, and ReadOnlySequence<byte> respectively; all three create a defensive internal copy so that the caller's buffer does not alias the stored key material. The copy is zeroed as soon as it has been encrypted.

Keeping plaintext off the heap

AsReadOnlySpan() and AsReadOnlyMemory() decrypt the key 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:

using System.Security.Cryptography;
using OnixLabs.Security.Cryptography;

using EcdsaPrivateKey privateKey = EcdsaPrivateKey.Create();

Span<byte> keyData = stackalloc byte[privateKey.Length];

try
{
    privateKey.CopyTo(keyData);
    // Use keyData...
}
finally
{
    CryptographicOperations.ZeroMemory(keyData);
}

The library follows the same pattern internally: ToString, ToString(IFormatProvider) and the ECDSA, ECDH, RSA and EdDSA operations decrypt the key into a temporary buffer (on the stack for keys of up to 256 bytes) and zero it after use.

Algorithm-specific capabilities — signing data, deriving shared secrets, deriving the corresponding public key, and all import/export formats — are expressed through the key interface family such as IPrivateKeyExportable, IPrivateKeyImportable<T>, and the algorithm interfaces (e.g. IEcdsaPrivateKey). The concrete subclasses implement the appropriate combination of those interfaces.

PrivateKey implements IDisposable. Always dispose private-key instances (or use a using statement) to ensure the in-memory key bytes are zeroed promptly. Reading KeyData or any method that accesses it after disposal throws ObjectDisposedException.

Equality and hash codes do not decrypt the key. Each instance computes the SHA-256 digest of its key bytes once, at construction, and equality compares those digests using System.Security.Cryptography.CryptographicOperations.FixedTimeEquals to avoid timing side-channels. Two instances are equal only when they share the same runtime type and identical key bytes.

ToString() returns a hexadecimal (Base16) encoding of the raw key bytes. An alternative encoding can be obtained by passing an IFormatProvider (such as a Base58 or Base64 provider) to ToString(IFormatProvider). For a self-describing representation that embeds the algorithm name, call ToNamedPrivateKey() to obtain a NamedPrivateKey.

Note PrivateKey uses value semantics: equality and hash codes are based on the runtime type and the digest of the key bytes, not reference identity. The == and != operators are defined accordingly.

Examples

Creating and using an ECDSA private key

The base class is abstract; work with a concrete subclass. The example below creates a fresh key pair, signs a payload, and then disposes both keys.

using System.Security.Cryptography;
using OnixLabs.Security.Cryptography;

// Generate a new ECDSA private key (default curve).
using EcdsaPrivateKey privateKey = EcdsaPrivateKey.Create();

// Derive the corresponding public key.
EcdsaPublicKey publicKey = privateKey.GetPublicKey();

byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, ONIXLabs!");

// Sign the data using SHA-256.
byte[] signature = privateKey.SignData(data, SHA256.Create());

// Verify the signature.
bool valid = publicKey.IsDataValid(signature, data, SHA256.Create());
Console.WriteLine(valid); // True

Obtaining a self-describing named key

using OnixLabs.Security.Cryptography;

using EcdsaPrivateKey privateKey = EcdsaPrivateKey.Create();

// Wrap in a NamedPrivateKey to carry the algorithm name alongside the key bytes.
NamedPrivateKey named = privateKey.ToNamedPrivateKey();

Console.WriteLine(named.AlgorithmName); // ECDSA
Console.WriteLine(named);               // ECDSA:<hex-encoded key bytes>

Comparing keys

using OnixLabs.Security.Cryptography;

using EcdsaPrivateKey a = EcdsaPrivateKey.Create();
using EcdsaPrivateKey b = EcdsaPrivateKey.Create();

Console.WriteLine(a == a); // True  (same instance)
Console.WriteLine(a == b); // False (different key material)

Constructors

Constructor Description
PrivateKey(ReadOnlySpan<byte>) Initializes a new instance of the PrivateKey class from a span of bytes. Protected; called from a derived type's constructor.
PrivateKey(ReadOnlyMemory<byte>) Initializes a new instance of the PrivateKey class from a memory region. Protected; called from a derived type's constructor.
PrivateKey(ReadOnlySequence<byte>) Initializes a new instance of the PrivateKey class from a byte sequence. Protected; called from a derived type's constructor.

PrivateKey(ReadOnlySpan<byte>)

protected PrivateKey(ReadOnlySpan<byte> keyData)

Initializes a new instance of the PrivateKey class. The provided span is copied into an internal ProtectedData wrapper; the span itself is not retained.

Parameter Type Description
keyData ReadOnlySpan<byte> The underlying key data of the cryptographic private key.

PrivateKey(ReadOnlyMemory<byte>)

protected PrivateKey(ReadOnlyMemory<byte> keyData)

Initializes a new instance of the PrivateKey class. The provided memory region is copied into an internal ProtectedData wrapper; the original memory is not retained.

Parameter Type Description
keyData ReadOnlyMemory<byte> The underlying key data of the cryptographic private key.

PrivateKey(ReadOnlySequence<byte>)

protected PrivateKey(ReadOnlySequence<byte> keyData)

Initializes a new instance of the PrivateKey class. The provided byte sequence is copied into an internal ProtectedData wrapper; the original sequence is not retained.

Parameter Type Description
keyData ReadOnlySequence<byte> The underlying key data of the cryptographic private key.

Properties

Property Type Description
Length int Gets the length of the key data, in bytes.
KeyData byte[] Gets the decrypted key bytes. Protected; accessible only to subclasses.

Length

public int Length { get; }

Gets the length of the cryptographic private key data, in bytes. Use it to size the buffer passed to CopyTo(Span<byte>). Reading Length does not decrypt the key.

KeyData

protected byte[] KeyData { get; }

Gets the cryptographic private key data by decrypting the in-memory ProtectedData store. The returned array is a fresh decryption each time the property is read; callers should zero it with CryptographicOperations.ZeroMemory when done. Prefer CopyTo(Span<byte>), which decrypts into a buffer the caller controls.

Exceptions

Exception Condition
ObjectDisposedException The current PrivateKey has been disposed.

Methods

Method Returns Description
AsReadOnlyMemory() ReadOnlyMemory<byte> Returns the key bytes as a read-only memory region.
AsReadOnlySpan() ReadOnlySpan<byte> Returns the key bytes as a read-only span.
CopyTo(Span<byte>) void Decrypts the key bytes into the specified buffer, without placing plaintext on the heap.
Dispose() void Releases the in-memory key material and suppresses finalization.
Dispose(bool) void Releases managed resources when disposing deterministically. Protected; override in derived types.
Equals(PrivateKey?) bool Determines whether this key is equal to another PrivateKey.
Equals(object?) bool Determines whether this key is equal to another object.
GetHashCode() int Returns a hash code derived from the runtime type and the digest of the key bytes.
ToNamedPrivateKey() NamedPrivateKey Creates a NamedPrivateKey from this instance. Abstract; implemented by each concrete subclass.
ToString() string Returns the Base16 (hexadecimal) representation of the key bytes.
ToString(IFormatProvider) string Returns the key bytes encoded using the supplied format provider.

AsReadOnlyMemory()

public ReadOnlyMemory<byte> AsReadOnlyMemory()

Returns the key bytes as a ReadOnlyMemory<byte>. Each call decrypts the key data 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 cryptographic private key bytes.

Exceptions

Exception Condition
ObjectDisposedException The current PrivateKey has been disposed.

AsReadOnlySpan()

public ReadOnlySpan<byte> AsReadOnlySpan()

Returns the key bytes as a ReadOnlySpan<byte>. Each call decrypts the key data 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> containing the cryptographic private key bytes.

Exceptions

Exception Condition
ObjectDisposedException The current PrivateKey has been disposed.

CopyTo(Span<byte>)

public void CopyTo(Span<byte> destination)

Copies the decrypted cryptographic private key data 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 key data, which must be at least Length bytes long.

Exceptions

Exception Condition
ObjectDisposedException The current PrivateKey has been disposed.
ArgumentException destination is shorter than Length.

Dispose()

public void Dispose()

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. Disposes the internal ProtectedData store, which zeroes and releases the encrypted key bytes, then suppresses GC finalization.

Dispose(bool)

protected virtual void Dispose(bool disposing)

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. When disposing is true, the managed ProtectedData store is disposed. Override this method in a derived class to release additional managed or unmanaged resources.

Parameter Type Description
disposing bool true when called from Dispose(); false when called from a finalizer.

Equals(PrivateKey?)

public bool Equals(PrivateKey? other)

Determines whether the current instance is equal to another PrivateKey. Two instances are equal when they have the same runtime type and the SHA-256 digests of their key bytes, computed once at construction, compare equal using CryptographicOperations.FixedTimeEquals, which avoids timing side-channels. Neither key is decrypted.

Returns — true if the instances are equal; otherwise, false.

Exceptions

Exception Condition
ObjectDisposedException The current PrivateKey or other has been disposed.

Equals(object?)

public override bool Equals(object? obj)

Determines whether the current instance is equal to another object. Delegates to Equals(PrivateKey?) when obj is a PrivateKey.

Returns — true if obj is an equal PrivateKey; otherwise, false.

Exceptions

Exception Condition
ObjectDisposedException The current PrivateKey or obj has been disposed.

GetHashCode()

public override int GetHashCode()

Returns a hash code for the current instance, combining the runtime type and the SHA-256 digest of the key bytes. The key is not decrypted. Like HashCode, the result is randomised per process and must not be persisted.

Returns — A 32-bit signed integer hash code.

Exceptions

Exception Condition
ObjectDisposedException The current PrivateKey has been disposed.

ToNamedPrivateKey()

public abstract NamedPrivateKey ToNamedPrivateKey()

Creates a new NamedPrivateKey from the current PrivateKey instance. Each concrete subclass implements this method to supply the appropriate algorithm name (for example, "ECDSA" or "RSA").

Returns — A NamedPrivateKey pairing this instance with its algorithm name.

ToString()

public override string ToString()

Returns a string representation of the key bytes encoded as uppercase hexadecimal (Base16, invariant culture).

Returns — A hexadecimal string representing the cryptographic private key bytes.

Exceptions

Exception Condition
ObjectDisposedException The current PrivateKey has been disposed.

ToString(IFormatProvider)

public string ToString(IFormatProvider provider)

Returns a string representation of the key bytes encoded using the supplied IFormatProvider. Pass a Base58, Base64, or other codec provider to obtain an alternative encoding.

Parameter Type Description
provider IFormatProvider The format provider that determines the output encoding.

Returns — A string representing the cryptographic private key bytes in the requested encoding.

Exceptions

Exception Condition
ObjectDisposedException The current PrivateKey has been disposed.

Operators

Operator Description
operator == Determines whether two PrivateKey instances are equal.
operator != Determines whether two PrivateKey instances are not equal.

operator ==

public static bool operator ==(PrivateKey? left, PrivateKey? right)

Performs an equality comparison between two PrivateKey instances. Returns true if left is equal to right; otherwise, false. Two null references are considered equal.

operator !=

public static bool operator !=(PrivateKey? left, PrivateKey? right)

Performs an inequality comparison between two PrivateKey instances. Returns true if left is not equal to right; otherwise, false.

See Also

ONIXLabs .NET Library


Clone this wiki locally