Skip to content

OnixLabs.Security.Cryptography.PublicKey

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

PublicKey Class

Represents the abstract base class for all asymmetric cryptographic public keys. EcdhPublicKey, EcdsaPublicKey, EddsaPublicKey, and RsaPublicKey all derive from this class.

Namespace OnixLabs.Security.Cryptography
Assembly OnixLabs.Security.Cryptography.dll (NuGet)
Inheritance object → PublicKey
Implements ICryptoPrimitive<PublicKey>, IValueEquatable<PublicKey>, IEquatable<PublicKey>, IBinaryConvertible
Derived EcdhPublicKey, EcdsaPublicKey, EddsaPublicKey, RsaPublicKey

Definition

public abstract partial class PublicKey : ICryptoPrimitive<PublicKey>

Remarks

PublicKey is the root of the asymmetric public-key hierarchy. Unlike PrivateKey, it does not implement IDisposable because public keys carry no sensitive material and do not require secure erasure.

Key bytes are held in a protected byte[] field. The constructor creates a defensive internal copy from the supplied ReadOnlySpan<byte>, ReadOnlyMemory<byte>, or ReadOnlySequence<byte> so that the caller's buffer does not alias the stored key material. Because the constructor is protected, only subclasses can instantiate PublicKey.

Algorithm-specific capabilities — signature verification, public-key import/export — are expressed through the key interface family such as IPublicKeyExportable, IPublicKeyImportable<T>, and the algorithm interfaces (e.g. IEcdsaPublicKey). The concrete subclasses implement the appropriate combination of those interfaces.

Equality comparisons use 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 ToNamedPublicKey() to obtain a NamedPublicKey. A Hash of the raw key bytes can be computed directly via GetHash(HashAlgorithm), which is useful for key fingerprinting.

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

Examples

Deriving a public key from a private key

Public keys are normally obtained by deriving them from their corresponding private key. The concrete private-key types expose a GetPublicKey() method for this purpose.

using OnixLabs.Security.Cryptography;

using EcdsaPrivateKey privateKey = EcdsaPrivateKey.Create();

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

Console.WriteLine(publicKey); // hex-encoded SubjectPublicKeyInfo bytes

Verifying a signature

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

using EcdsaPrivateKey privateKey = EcdsaPrivateKey.Create();
EcdsaPublicKey publicKey = privateKey.GetPublicKey();

byte[] data      = System.Text.Encoding.UTF8.GetBytes("Hello, ONIXLabs!");
byte[] signature = privateKey.SignData(data, SHA256.Create());

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

Computing a key fingerprint

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

using EcdsaPrivateKey privateKey = EcdsaPrivateKey.Create();
EcdsaPublicKey publicKey = privateKey.GetPublicKey();

Hash fingerprint = publicKey.GetHash(SHA256.Create());
Console.WriteLine(fingerprint); // SHA2-256:<hex>

Obtaining a self-describing named key

using OnixLabs.Security.Cryptography;

using EcdsaPrivateKey privateKey = EcdsaPrivateKey.Create();
EcdsaPublicKey publicKey = privateKey.GetPublicKey();

NamedPublicKey named = publicKey.ToNamedPublicKey();

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

Comparing keys

using OnixLabs.Security.Cryptography;

using EcdsaPrivateKey pk1 = EcdsaPrivateKey.Create();
using EcdsaPrivateKey pk2 = EcdsaPrivateKey.Create();

EcdsaPublicKey pub1 = pk1.GetPublicKey();
EcdsaPublicKey pub2 = pk2.GetPublicKey();
EcdsaPublicKey pub1b = pk1.GetPublicKey();

Console.WriteLine(pub1 == pub1b); // True  (same key material)
Console.WriteLine(pub1 == pub2);  // False (different key material)

Constructors

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

PublicKey(ReadOnlySpan<byte>)

protected PublicKey(ReadOnlySpan<byte> keyData)

Initializes a new instance of the PublicKey class. The provided span is copied to an internal array; the span itself is not retained.

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

PublicKey(ReadOnlyMemory<byte>)

protected PublicKey(ReadOnlyMemory<byte> keyData)

Initializes a new instance of the PublicKey class. The provided memory region is copied to an internal array; the original memory is not retained.

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

PublicKey(ReadOnlySequence<byte>)

protected PublicKey(ReadOnlySequence<byte> keyData)

Initializes a new instance of the PublicKey class. The provided byte sequence is copied to an internal array; the original sequence is not retained.

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

Properties

Property Type Description
KeyData byte[] Gets the raw key bytes. Protected; accessible only to subclasses.

KeyData

protected byte[] KeyData { get; }

Gets the underlying byte array containing the cryptographic public key data. The property returns the stored array directly; subclasses should not mutate the returned array.

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.
Equals(PublicKey?) bool Determines whether this key is equal to another PublicKey.
Equals(object?) bool Determines whether this key is equal to another object.
GetHash(HashAlgorithm) Hash Computes a hash of the key bytes using the specified algorithm.
GetHashCode() int Returns a hash code derived from the runtime type and key bytes.
ToNamedPublicKey() NamedPublicKey Creates a NamedPublicKey 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>.

Returns — A ReadOnlyMemory<byte> containing the cryptographic public key bytes.

AsReadOnlySpan()

public ReadOnlySpan<byte> AsReadOnlySpan()

Returns the key bytes as a ReadOnlySpan<byte>.

Returns — A ReadOnlySpan<byte> containing the cryptographic public key bytes.

Equals(PublicKey?)

public bool Equals(PublicKey? other)

Determines whether the current instance is equal to another PublicKey. Two instances are equal when they have the same runtime type and their key bytes compare equal using CryptographicOperations.FixedTimeEquals, which avoids timing side-channels.

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

Equals(object?)

public override bool Equals(object? obj)

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

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

GetHash(HashAlgorithm)

public Hash GetHash(HashAlgorithm algorithm)

Computes a Hash of the raw public key bytes using the specified hash algorithm. This is useful for generating a compact, algorithm-independent key fingerprint.

Parameter Type Description
algorithm HashAlgorithm The hash algorithm used to hash the public key data.

Returns — A Hash representing the digest of the public key bytes.

Exceptions

Exception Condition
CryptographicException The hash could not be computed for the public key data.

GetHashCode()

public override int GetHashCode()

Returns a hash code for the current instance, combining the runtime type and the content of the key bytes. Equal values produce equal hash codes; like HashCode, the result is randomised per process and must not be persisted.

Returns — A 32-bit signed integer hash code.

ToNamedPublicKey()

public abstract NamedPublicKey ToNamedPublicKey()

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

Returns — A NamedPublicKey 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 public key bytes.

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 public key bytes in the requested encoding.

Operators

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

operator ==

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

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

operator !=

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

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

See Also

ONIXLabs .NET Library


Clone this wiki locally