Repository navigation
OnixLabs.Security.Cryptography.RsaPublicKey
Represents an RSA cryptographic public key. Supports digital signature verification in both PKCS #1 v1.5 and PSS padding modes, and provides key import and export in raw SubjectPublicKeyInfo (SPKI) binary and PEM formats.
| Namespace | OnixLabs.Security.Cryptography |
| Assembly | OnixLabs.Security.Cryptography.dll (NuGet) |
| Inheritance |
object → PublicKey → RsaPublicKey
|
| Implements |
IRsaPublicKey, ISpanParsable<RsaPublicKey>, IPublicKeyImportable<RsaPublicKey>, IPublicKeyExportable, ICryptoPrimitive<PublicKey>, IValueEquatable<PublicKey>, IEquatable<PublicKey>, IBinaryConvertible
|
public sealed partial class RsaPublicKey : PublicKey, IRsaPublicKey, ISpanParsable<RsaPublicKey>RsaPublicKey is the concrete RSA implementation of PublicKey. It stores raw RSA public key material (PKCS #1 DER) in the inherited protected KeyData byte array. Unlike RsaPrivateKey, RsaPublicKey does not implement IDisposable because public keys carry no sensitive material.
Verification — the type exposes two families of operation:
-
IsDataValid/IsHashValid— returnboolwithout throwing; suitable for conditional logic. -
VerifyData/VerifyHash— throwCryptographicExceptionif verification fails; suitable for fail-fast paths.
All verification methods require both a HashAlgorithmName and an RSASignaturePadding. The padding mode must match the one used when the data was signed:
-
RSASignaturePadding.Pkcs1— deterministic PKCS #1 v1.5 padding. -
RSASignaturePadding.Pss— probabilistic PSS padding.
Signatures may be supplied as either a raw ReadOnlySpan<byte> or a DigitalSignature value.
Obtaining an instance — derive a public key from a private key via RsaPrivateKey.GetPublicKey(); import existing material via Import or ImportPem; or parse a hex-encoded key string with Parse / TryParse.
Export formats — the key can be exported as:
| Method | Format |
|---|---|
Export() |
SubjectPublicKeyInfo (SPKI) DER bytes |
ExportPem() |
RFC 7468 PEM (PUBLIC KEY) |
ToString() returns the raw key bytes encoded as uppercase hexadecimal (Base16). Call ToNamedPublicKey() to obtain a NamedPublicKey tagged with the algorithm name "RSA". A key fingerprint can be computed via the inherited GetHash(HashAlgorithm) method.
Note
RsaPublicKeyinherits value semantics fromPublicKey: equality and hash codes are based on the runtime type and key bytes, not reference identity.
using System.Security.Cryptography;
using OnixLabs.Security.Cryptography;
// Generate a new RSA private key and derive the public key.
using RsaPrivateKey privateKey = RsaPrivateKey.Create();
RsaPublicKey publicKey = privateKey.GetPublicKey();
byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, ONIXLabs!");
// Sign using SHA-256 and PSS padding.
byte[] signature = privateKey.SignData(
data,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pss);
// Verify: returns true/false without throwing.
bool valid = publicKey.IsDataValid(
signature,
data,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pss);
Console.WriteLine(valid); // True
// Verify: throws CryptographicException if invalid.
publicKey.VerifyData(
signature,
data,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pss);using System.Security.Cryptography;
using OnixLabs.Security.Cryptography;
using RsaPrivateKey privateKey = RsaPrivateKey.Create();
RsaPublicKey publicKey = privateKey.GetPublicKey();
byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, ONIXLabs!");
byte[] hashBytes = SHA256.HashData(data);
// Sign the pre-computed hash.
byte[] signature = privateKey.SignHash(
hashBytes,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pss);
// Verify the pre-computed hash.
bool valid = publicKey.IsHashValid(
signature,
hashBytes,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pss);
Console.WriteLine(valid); // Trueusing System.Security.Cryptography;
using OnixLabs.Security.Cryptography;
using RsaPrivateKey privateKey = RsaPrivateKey.Create();
RsaPublicKey original = privateKey.GetPublicKey();
// Export as SubjectPublicKeyInfo DER.
byte[] spki = original.Export();
// Re-import.
RsaPublicKey restored = RsaPublicKey.Import(spki);
Console.WriteLine(original == restored); // True
// Compute a key fingerprint.
Hash fingerprint = restored.GetHash(SHA256.Create());
Console.WriteLine(fingerprint); // SHA2-256:<hex>using OnixLabs.Security.Cryptography;
using RsaPrivateKey privateKey = RsaPrivateKey.Create();
RsaPublicKey publicKey = privateKey.GetPublicKey();
NamedPublicKey named = publicKey.ToNamedPublicKey();
Console.WriteLine(named.AlgorithmName); // RSA
Console.WriteLine(named); // RSA:<hex-encoded key bytes>| Constructor | Description |
|---|---|
RsaPublicKey(ReadOnlySpan<byte>) |
Initializes a new instance from a span of bytes. |
RsaPublicKey(ReadOnlyMemory<byte>) |
Initializes a new instance from a memory region. |
RsaPublicKey(ReadOnlySequence<byte>) |
Initializes a new instance from a byte sequence. |
public RsaPublicKey(ReadOnlySpan<byte> keyData)Initializes a new instance of the RsaPublicKey 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 RSA cryptographic public key. |
public RsaPublicKey(ReadOnlyMemory<byte> keyData)Initializes a new instance of the RsaPublicKey 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 RSA cryptographic public key. |
public RsaPublicKey(ReadOnlySequence<byte> keyData)Initializes a new instance of the RsaPublicKey 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 RSA cryptographic public key. |
| Method | Returns | Description |
|---|---|---|
Import(ReadOnlySpan<byte>) |
RsaPublicKey |
Imports an RSA public key from a raw SubjectPublicKeyInfo span. |
Import(ReadOnlySpan<byte>, out int) |
RsaPublicKey |
Imports an RSA public key from a raw SubjectPublicKeyInfo span; reports bytes read. |
Import(IBinaryConvertible) |
RsaPublicKey |
Imports an RSA public key from an IBinaryConvertible. |
Import(IBinaryConvertible, out int) |
RsaPublicKey |
Imports an RSA public key from an IBinaryConvertible; reports bytes read. |
ImportPem(ReadOnlySpan<char>) |
RsaPublicKey |
Imports a public key from unencrypted RFC 7468 PEM-encoded text. |
ImportPem(ReadOnlySpan<char>, ReadOnlySpan<char>) |
RsaPublicKey |
Imports a public key from encrypted PEM using a char password. |
ImportPem(ReadOnlySpan<char>, ReadOnlySpan<byte>) |
RsaPublicKey |
Imports a public key from encrypted PEM using a byte password. |
Parse(string, IFormatProvider?) |
RsaPublicKey |
Parses a hex-encoded key string into an RsaPublicKey. |
Parse(ReadOnlySpan<char>, IFormatProvider?) |
RsaPublicKey |
Parses a hex-encoded key span into an RsaPublicKey. |
TryParse(string?, IFormatProvider?, out RsaPublicKey) |
bool |
Attempts to parse a hex-encoded key string into an RsaPublicKey. |
TryParse(ReadOnlySpan<char>, IFormatProvider?, out RsaPublicKey) |
bool |
Attempts to parse a hex-encoded key span into an RsaPublicKey. |
public static RsaPublicKey Import(ReadOnlySpan<byte> data)
public static RsaPublicKey Import(ReadOnlySpan<byte> data, out int bytesRead)
public static RsaPublicKey Import(IBinaryConvertible data)
public static RsaPublicKey Import(IBinaryConvertible data, out int bytesRead)Imports an RSA public key from its SubjectPublicKeyInfo (SPKI) DER-encoded binary representation.
| Parameter | Type | Description |
|---|---|---|
data |
ReadOnlySpan<byte> or IBinaryConvertible
|
The SPKI DER-encoded RSA public key data to import. |
bytesRead |
out int |
(bytesRead overloads) Receives the number of bytes consumed from data. |
Returns — A new RsaPublicKey instance containing the imported key.
Exceptions
| Exception | Condition |
|---|---|
CryptographicException |
data does not contain a valid RSA SubjectPublicKeyInfo structure. |
public static RsaPublicKey ImportPem(ReadOnlySpan<char> data)
public static RsaPublicKey ImportPem(ReadOnlySpan<char> data, ReadOnlySpan<char> password)
public static RsaPublicKey ImportPem(ReadOnlySpan<char> data, ReadOnlySpan<byte> password)Imports an RSA public key from RFC 7468 PEM-encoded text. The PEM label determines the format decoded (typically PUBLIC KEY, i.e. SPKI). The two-argument overloads additionally decrypt encrypted PEM blocks.
| Parameter | Type | Description |
|---|---|---|
data |
ReadOnlySpan<char> |
The PEM-encoded public key data to import. |
password |
ReadOnlySpan<char> or ReadOnlySpan<byte>
|
(encrypted overloads) The password required to decrypt the key. |
Returns — A new RsaPublicKey instance containing the imported key.
Exceptions
| Exception | Condition |
|---|---|
CryptographicException |
The PEM data is malformed, the label is unsupported, or decryption failed. |
public static RsaPublicKey Parse(string value, IFormatProvider? provider = null)Parses a string containing the hex-encoded (Base16) raw key bytes into a new RsaPublicKey instance. If provider is null, Base16FormatProvider.Invariant is used.
| Parameter | Type | Description |
|---|---|---|
value |
string |
The hex-encoded string representing the RSA public key. |
provider |
IFormatProvider? |
The format provider that determines how value is decoded. |
Returns — A new RsaPublicKey decoded from value.
Exceptions
| Exception | Condition |
|---|---|
FormatException |
value is not a valid encoded key string for the given provider. |
public static RsaPublicKey Parse(ReadOnlySpan<char> value, IFormatProvider? provider = null)Parses a span containing the hex-encoded (Base16) raw key bytes into a new RsaPublicKey instance. If provider is null, Base16FormatProvider.Invariant is used.
| Parameter | Type | Description |
|---|---|---|
value |
ReadOnlySpan<char> |
The hex-encoded character span representing the RSA public key. |
provider |
IFormatProvider? |
The format provider that determines how value is decoded. |
Returns — A new RsaPublicKey decoded from value.
Exceptions
| Exception | Condition |
|---|---|
FormatException |
value is not a valid encoded key span for the given provider. |
public static bool TryParse(string? value, IFormatProvider? provider, out RsaPublicKey result)Attempts to parse a string containing the hex-encoded (Base16) raw key bytes into a new RsaPublicKey instance. Does not throw on failure.
| Parameter | Type | Description |
|---|---|---|
value |
string? |
The hex-encoded string representing the RSA public key, or null. |
provider |
IFormatProvider? |
The format provider that determines how value is decoded. |
result |
out RsaPublicKey |
When the method returns, contains the parsed RsaPublicKey, or a default-initialized instance if parsing failed. |
Returns — true if value was successfully parsed; otherwise, false.
public static bool TryParse(ReadOnlySpan<char> value, IFormatProvider? provider, out RsaPublicKey result)Attempts to parse a span containing the hex-encoded (Base16) raw key bytes into a new RsaPublicKey instance. Does not throw on failure.
| Parameter | Type | Description |
|---|---|---|
value |
ReadOnlySpan<char> |
The hex-encoded character span representing the RSA public key. |
provider |
IFormatProvider? |
The format provider that determines how value is decoded. |
result |
out RsaPublicKey |
When the method returns, contains the parsed RsaPublicKey, or a default-initialized instance if parsing failed. |
Returns — true if value was successfully parsed; otherwise, false.
Inherited members that are unchanged — AsReadOnlyMemory(), AsReadOnlySpan(), Equals(PublicKey?), Equals(object?), GetHash(HashAlgorithm), GetHashCode(), ToString(), ToString(IFormatProvider), and the == / != operators — are documented on the PublicKey page.
public byte[] Export()Exports the RSA public key as SubjectPublicKeyInfo (SPKI) DER-encoded bytes (equivalent to RSA.ExportSubjectPublicKeyInfo()).
Returns — A byte[] containing the RSA public key in SPKI DER format.
Exceptions
| Exception | Condition |
|---|---|
CryptographicException |
The key material could not be exported. |
public string ExportPem()Exports the RSA public key as an RFC 7468 PEM string with the PUBLIC KEY label (SubjectPublicKeyInfo).
Returns — A string containing the PEM-encoded RSA public key.
Exceptions
| Exception | Condition |
|---|---|
CryptographicException |
The key material could not be exported. |
public bool IsDataValid(ReadOnlySpan<byte> signature, ReadOnlySpan<byte> data, HashAlgorithmName algorithm, RSASignaturePadding padding)
public bool IsDataValid(ReadOnlySpan<byte> signature, ReadOnlySpan<byte> data, int offset, int count, HashAlgorithmName algorithm, RSASignaturePadding padding)
public bool IsDataValid(ReadOnlySpan<byte> signature, Stream data, HashAlgorithmName algorithm, RSASignaturePadding padding)
public bool IsDataValid(ReadOnlySpan<byte> signature, IBinaryConvertible data, HashAlgorithmName algorithm, RSASignaturePadding padding)
public bool IsDataValid(DigitalSignature signature, ReadOnlySpan<byte> data, HashAlgorithmName algorithm, RSASignaturePadding padding)
public bool IsDataValid(DigitalSignature signature, ReadOnlySpan<byte> data, int offset, int count, HashAlgorithmName algorithm, RSASignaturePadding padding)
public bool IsDataValid(DigitalSignature signature, Stream data, HashAlgorithmName algorithm, RSASignaturePadding padding)
public bool IsDataValid(DigitalSignature signature, IBinaryConvertible data, HashAlgorithmName algorithm, RSASignaturePadding padding)Determines whether the specified data was signed by the RSA private key corresponding to this public key, using the specified hash algorithm and padding. Returns true or false; does not throw on a verification failure.
| Parameter | Type | Description |
|---|---|---|
signature |
ReadOnlySpan<byte> or DigitalSignature
|
The signature to validate. |
data |
ReadOnlySpan<byte> / Stream / IBinaryConvertible
|
The unsigned data to validate. |
offset |
int |
(slice overloads) The offset into the span from which to begin reading. |
count |
int |
(slice overloads) The number of bytes to read from the span. |
algorithm |
HashAlgorithmName |
The hash algorithm used when signing. |
padding |
RSASignaturePadding |
The RSA signature padding mode used when signing. |
Returns — true if the signature is valid for the supplied data; otherwise false.
public bool IsHashValid(ReadOnlySpan<byte> signature, ReadOnlySpan<byte> hash, HashAlgorithmName algorithm, RSASignaturePadding padding)
public bool IsHashValid(ReadOnlySpan<byte> signature, Hash hash, HashAlgorithmName algorithm, RSASignaturePadding padding)
public bool IsHashValid(DigitalSignature signature, ReadOnlySpan<byte> hash, HashAlgorithmName algorithm, RSASignaturePadding padding)
public bool IsHashValid(DigitalSignature signature, Hash hash, HashAlgorithmName algorithm, RSASignaturePadding padding)Determines whether the specified pre-computed hash was signed by the RSA private key corresponding to this public key. Returns true or false; does not throw on a verification failure.
| Parameter | Type | Description |
|---|---|---|
signature |
ReadOnlySpan<byte> or DigitalSignature
|
The signature to validate. |
hash |
ReadOnlySpan<byte> or Hash
|
The pre-computed hash to validate. |
algorithm |
HashAlgorithmName |
The hash algorithm used when signing. |
padding |
RSASignaturePadding |
The RSA signature padding mode used when signing. |
Returns — true if the signature is valid for the supplied hash; otherwise false.
public void VerifyData(ReadOnlySpan<byte> signature, ReadOnlySpan<byte> data, HashAlgorithmName algorithm, RSASignaturePadding padding)
public void VerifyData(ReadOnlySpan<byte> signature, ReadOnlySpan<byte> data, int offset, int count, HashAlgorithmName algorithm, RSASignaturePadding padding)
public void VerifyData(ReadOnlySpan<byte> signature, Stream data, HashAlgorithmName algorithm, RSASignaturePadding padding)
public void VerifyData(ReadOnlySpan<byte> signature, IBinaryConvertible data, HashAlgorithmName algorithm, RSASignaturePadding padding)
public void VerifyData(DigitalSignature signature, ReadOnlySpan<byte> data, HashAlgorithmName algorithm, RSASignaturePadding padding)
public void VerifyData(DigitalSignature signature, ReadOnlySpan<byte> data, int offset, int count, HashAlgorithmName algorithm, RSASignaturePadding padding)
public void VerifyData(DigitalSignature signature, Stream data, HashAlgorithmName algorithm, RSASignaturePadding padding)
public void VerifyData(DigitalSignature signature, IBinaryConvertible data, HashAlgorithmName algorithm, RSASignaturePadding padding)Verifies that the specified data was signed by the RSA private key corresponding to this public key. Throws CryptographicException if verification fails. Use this overload family on fail-fast paths where an invalid signature should abort the operation.
Parameters match those of the IsDataValid overloads above.
Exceptions
| Exception | Condition |
|---|---|
CryptographicException |
The signature is not valid for the supplied data and key. |
public void VerifyHash(ReadOnlySpan<byte> signature, ReadOnlySpan<byte> hash, HashAlgorithmName algorithm, RSASignaturePadding padding)
public void VerifyHash(ReadOnlySpan<byte> signature, Hash hash, HashAlgorithmName algorithm, RSASignaturePadding padding)
public void VerifyHash(DigitalSignature signature, ReadOnlySpan<byte> hash, HashAlgorithmName algorithm, RSASignaturePadding padding)
public void VerifyHash(DigitalSignature signature, Hash hash, HashAlgorithmName algorithm, RSASignaturePadding padding)Verifies that the specified pre-computed hash was signed by the RSA private key corresponding to this public key. Throws CryptographicException if verification fails.
Parameters match those of the IsHashValid overloads above.
Exceptions
| Exception | Condition |
|---|---|
CryptographicException |
The signature is not valid for the supplied hash and key. |
public override NamedPublicKey ToNamedPublicKey()Creates a new NamedPublicKey that pairs this RsaPublicKey with the algorithm name "RSA".
Returns — A NamedPublicKey with AlgorithmName equal to "RSA" and PublicKey equal to this instance.
| Operator | Description |
|---|---|
implicit operator RsaPublicKey(ReadOnlySpan<byte>) |
Implicitly converts a ReadOnlySpan<byte> to an RsaPublicKey. |
implicit operator RsaPublicKey(ReadOnlyMemory<byte>) |
Implicitly converts a ReadOnlyMemory<byte> to an RsaPublicKey. |
implicit operator RsaPublicKey(ReadOnlySequence<byte>) |
Implicitly converts a ReadOnlySequence<byte> to an RsaPublicKey. |
public static implicit operator RsaPublicKey(ReadOnlySpan<byte> value)Creates a new RsaPublicKey instance from the specified ReadOnlySpan<byte> value. Equivalent to calling the RsaPublicKey(ReadOnlySpan<byte>) constructor.
public static implicit operator RsaPublicKey(ReadOnlyMemory<byte> value)Creates a new RsaPublicKey instance from the specified ReadOnlyMemory<byte> value. Equivalent to calling the RsaPublicKey(ReadOnlyMemory<byte>) constructor.
public static implicit operator RsaPublicKey(ReadOnlySequence<byte> value)Creates a new RsaPublicKey instance from the specified ReadOnlySequence<byte> value. Equivalent to calling the RsaPublicKey(ReadOnlySequence<byte>) constructor.
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