StormByte-Crypto 3.1.0
C++26 cryptography module of the StormByte suite
Loading...
Searching...
No Matches
StormByte::Crypto::X509::Certificate Class Reference

Immutable, strictly DER-parsed X.509 certificate. More...

#include <StormByte/crypto/x509/certificate.hxx>

Public Member Functions

Construction
 Certificate () noexcept
 Empty certificate; it has no DER and never verifies.
 Certificate (const Certificate &other)
 Copy constructor.
 Certificate (Certificate &&other) noexcept
 Move constructor.
 ~Certificate () noexcept
 Destructor.
Certificate & operator= (const Certificate &other)
 Copy assignment.
Certificate & operator= (Certificate &&other) noexcept
 Move assignment.
bool operator== (const Certificate &other) const noexcept
 Compares the DER encodings.
Fields
unsigned Version () const noexcept
 Returns the certificate version.
Safe::Binary SerialNumber () const
 Returns the serial number.
Safe::String SubjectCommonName () const
 Returns the subject common name.
bool HasUniqueSubjectCommonName (std::string_view expected) const noexcept
 Matches exactly one subject CN against a byte-exact identity.
Safe::String IssuerCommonName () const
 Returns the issuer common name.
TimePoint NotBefore () const noexcept
 Returns the start of the validity period.
TimePoint NotAfter () const noexcept
 Returns the end of the validity period.
bool IsCA () const noexcept
 Tells whether basicConstraints marks the certificate as a CA.
Safe::Optional< std::uint32_t > PathLength () const
 Returns the basicConstraints path length constraint.
bool HasKeyUsage (KeyUsage usage) const noexcept
 Tells whether the key may be used for usage.
KeyPair::Generic::PointerType PublicKey () const noexcept
 Returns the subject public key.
Verification
bool IsValidAt (TimePoint at) const noexcept
 Checks the validity period.
bool IsIssuedBy (const Certificate &issuer) const noexcept
 Checks name chaining and the signature against issuer.
bool VerifyChain (std::span< const Certificate > intermediates, const Certificate &anchor, TimePoint at) const noexcept
 Verifies this certificate up to a trusted anchor.
bool VerifyChain (std::span< const Certificate > intermediates, const Certificate &anchor) const noexcept
 Verifies this certificate up to a trusted anchor at the current time.
ExpectedPurpose VerifyTLSPurpose (TLSRole role) const
 Checks only EKU and KU for a TLS 1.3 certificate signing role.
ExpectedPurpose VerifyCodeSigningPurpose () const
 Checks only EKU and KU for code signing.
bool VerifyDetachedSignature (DetachedSignatureAlgorithm algorithm, std::span< const std::byte > message, std::span< const std::byte > signature) const noexcept
 Verifies a detached signature with this certificate's public key.
Identity
ExpectedSubjectAltNames SubjectAltNames () const
 Extracts the supported entries of the subjectAltName extension.
ExpectedIdentity VerifyDNSName (std::string_view expected) const
 Checks that the certificate asserts an expected DNS host name.
ExpectedIdentity VerifyIPAddress (std::span< const std::byte > expected) const
 Checks that the certificate asserts an expected IP address.

Friends

class TLSPeerVerifier
 Additive peer composition shares immutable parser state.
class RevocationVerifier
 Offline CRL/OCSP verification shares parsed certificate state.

Encoding

Safe::Binary Save (KeyPair::StorageFormat format=KeyPair::StorageFormat::PEM) const
 Encodes the certificate.
const Safe::Binary & Der () const noexcept
 Returns the original DER encoding.
static bool Parse (std::span< const std::byte > der, Certificate &out) noexcept
 Parses a single DER certificate; see also X509::Load.

Detailed Description

Immutable, strictly DER-parsed X.509 certificate.

Supported signatures: ecdsa-with-SHA256/384/512 and sha256/384/512WithRSAEncryption (PKCS#1 v1.5). Other algorithms load but never verify. Names are compared byte-for-byte, and revocation (CRL/OCSP) and name constraints are not processed.

Note
Certificates are public data; unlike keys they use StormByte::Safe::Binary.
Conditionally DLL-safe: all fields are Safe or trivial and value operations are defined out of line in Crypto.

Constructor & Destructor Documentation

◆ Certificate() [1/3]

StormByte::Crypto::X509::Certificate::Certificate ( )
noexcept

Empty certificate; it has no DER and never verifies.

◆ Certificate() [2/3]

StormByte::Crypto::X509::Certificate::Certificate ( const Certificate & other)

Copy constructor.

Parameters
otherCertificate to copy.

◆ Certificate() [3/3]

StormByte::Crypto::X509::Certificate::Certificate ( Certificate && other)
noexcept

Move constructor.

Parameters
otherCertificate to move.

◆ ~Certificate()

StormByte::Crypto::X509::Certificate::~Certificate ( )
noexcept

Destructor.

Member Function Documentation

◆ Der()

const Safe::Binary & StormByte::Crypto::X509::Certificate::Der ( ) const
noexcept

Returns the original DER encoding.

Returns
DER bytes.

◆ HasKeyUsage()

bool StormByte::Crypto::X509::Certificate::HasKeyUsage ( KeyUsage usage) const
noexcept

Tells whether the key may be used for usage.

Parameters
usageUsage to test.
Returns
true when the bit is set, or when keyUsage is absent (unrestricted).

◆ HasUniqueSubjectCommonName()

bool StormByte::Crypto::X509::Certificate::HasUniqueSubjectCommonName ( std::string_view expected) const
noexcept

Matches exactly one subject CN against a byte-exact identity.

Parameters
expectedNonempty expected common name.
Returns
false for a missing, repeated, malformed or different CN.
Note
This does not verify the certificate's chain, validity or purpose.

◆ IsCA()

bool StormByte::Crypto::X509::Certificate::IsCA ( ) const
noexcept

Tells whether basicConstraints marks the certificate as a CA.

Returns
true for cA = TRUE.

◆ IsIssuedBy()

bool StormByte::Crypto::X509::Certificate::IsIssuedBy ( const Certificate & issuer) const
noexcept

Checks name chaining and the signature against issuer.

Parameters
issuerCandidate issuer.
Returns
true when the issuer name matches the subject of issuer and its key verifies this certificate's signature.
Note
Does not check validity, CA flags or key usage; use VerifyChain.

◆ IssuerCommonName()

Safe::String StormByte::Crypto::X509::Certificate::IssuerCommonName ( ) const

Returns the issuer common name.

Returns
First CN attribute, or empty when absent or not a string type.

◆ IsValidAt()

bool StormByte::Crypto::X509::Certificate::IsValidAt ( TimePoint at) const
noexcept

Checks the validity period.

Parameters
atInstant to test.
Returns
true when notBefore <= at <= notAfter.

◆ NotAfter()

TimePoint StormByte::Crypto::X509::Certificate::NotAfter ( ) const
noexcept

Returns the end of the validity period.

Returns
notAfter, inclusive.

◆ NotBefore()

TimePoint StormByte::Crypto::X509::Certificate::NotBefore ( ) const
noexcept

Returns the start of the validity period.

Returns
notBefore.

◆ operator=() [1/2]

Certificate & StormByte::Crypto::X509::Certificate::operator= ( Certificate && other)
noexcept

Move assignment.

Parameters
otherCertificate to move.
Returns
Reference to this certificate.

◆ operator=() [2/2]

Certificate & StormByte::Crypto::X509::Certificate::operator= ( const Certificate & other)

Copy assignment.

Parameters
otherCertificate to copy.
Returns
Reference to this certificate.

◆ operator==()

bool StormByte::Crypto::X509::Certificate::operator== ( const Certificate & other) const
noexcept

Compares the DER encodings.

Parameters
otherCertificate to compare.
Returns
true when both encodings are identical.

◆ Parse()

bool StormByte::Crypto::X509::Certificate::Parse ( std::span< const std::byte > der,
Certificate & out )
staticnoexcept

Parses a single DER certificate; see also X509::Load.

Parameters
derCandidate DER bytes, without trailing data.
outDestination; reset to an empty certificate on failure.
Returns
false on malformed input.

◆ PathLength()

Safe::Optional< std::uint32_t > StormByte::Crypto::X509::Certificate::PathLength ( ) const

Returns the basicConstraints path length constraint.

Returns
Maximum number of intermediate CAs below this one, or empty when unlimited.

◆ PublicKey()

KeyPair::Generic::PointerType StormByte::Crypto::X509::Certificate::PublicKey ( ) const
noexcept

Returns the subject public key.

Returns
Public-only keypair (elliptic-curve keys load as KeyPair::Type::ECC), or null when unsupported.

◆ Save()

Safe::Binary StormByte::Crypto::X509::Certificate::Save ( KeyPair::StorageFormat format = KeyPair::StorageFormat::PEM) const

Encodes the certificate.

Parameters
formatPEM (CERTIFICATE block, 64-column Base64) or DER.
Returns
Encoded certificate.

◆ SerialNumber()

Safe::Binary StormByte::Crypto::X509::Certificate::SerialNumber ( ) const

Returns the serial number.

Returns
Big-endian two's-complement INTEGER contents.

◆ SubjectAltNames()

ExpectedSubjectAltNames StormByte::Crypto::X509::Certificate::SubjectAltNames ( ) const

Extracts the supported entries of the subjectAltName extension.

Returns
dNSName and iPAddress entries in certificate order, or an error.
Exceptions
StormByte::Safe::AllocationErrorEntry or error storage cannot be allocated.

The whole extension is validated strictly: a non-empty DER SEQUENCE of general names with known context tags, non-empty contents, dNSName values that are valid ASCII host names (labels of letters, digits and inner hyphens, at most 63 bytes each, 253 in total, no trailing dot, final label not all digits) or a wildcard whose complete leftmost label is * over at least two further labels, and iPAddress values of exactly 4 or 16 bytes. Other well-formed general-name kinds (email, URI, directory, other) are skipped. Any malformed entry fails the whole call with IdentityError::MalformedSubjectAltName; an absent extension yields IdentityError::MissingSubjectAltName. The subject common name is never consulted. Duplicate extensions are already rejected by Parse.

◆ SubjectCommonName()

Safe::String StormByte::Crypto::X509::Certificate::SubjectCommonName ( ) const

Returns the subject common name.

Returns
First CN attribute, or empty when absent or not a string type.

◆ VerifyChain() [1/2]

bool StormByte::Crypto::X509::Certificate::VerifyChain ( std::span< const Certificate > intermediates,
const Certificate & anchor ) const
noexcept

Verifies this certificate up to a trusted anchor at the current time.

Parameters
intermediatesUntrusted CAs ordered from the issuer of this certificate upwards.
anchorTrusted CA that issued the last intermediate (or this certificate).
Returns
true when every link verifies.

◆ VerifyChain() [2/2]

bool StormByte::Crypto::X509::Certificate::VerifyChain ( std::span< const Certificate > intermediates,
const Certificate & anchor,
TimePoint at ) const
noexcept

Verifies this certificate up to a trusted anchor.

Parameters
intermediatesUntrusted CAs ordered from the issuer of this certificate upwards.
anchorTrusted CA that issued the last intermediate (or this certificate).
atInstant used for validity periods.
Returns
true when every link verifies.

Every certificate, the anchor included, must be valid at at and carry no unrecognized critical extension. Every issuer, the anchor included, must be a version 3 CA allowed to sign certificates whose path length constraint covers the CAs below it. The anchor's own signature is not checked. This certificate's key usage is left to the caller.

◆ VerifyCodeSigningPurpose()

ExpectedPurpose StormByte::Crypto::X509::Certificate::VerifyCodeSigningPurpose ( ) const

Checks only EKU and KU for code signing.

Returns
Success when usage permits code signing, or a PurposeError.
Exceptions
StormByte::Safe::AllocationErrorError storage cannot be allocated.

EKU must be present and explicitly contain codeSigning (1.3.6.1.5.5.7.3.3); anyExtendedKeyUsage is insufficient. If KU is present, it must be strict DER and include digitalSignature. Errors are checked in order: empty certificate, malformed EKU, malformed KU, denied EKU, denied KU.

Note
This does not authenticate the certificate, validate its chain or validity, classify it as a leaf, check critical extensions, or verify its identity or a signature. Those checks are separate.

◆ VerifyDetachedSignature()

bool StormByte::Crypto::X509::Certificate::VerifyDetachedSignature ( DetachedSignatureAlgorithm algorithm,
std::span< const std::byte > message,
std::span< const std::byte > signature ) const
noexcept

Verifies a detached signature with this certificate's public key.

Parameters
algorithmRequired signature algorithm and encoding.
messageExact signed bytes.
signatureDetached signature bytes.
Returns
true only if the supported algorithm and public key verify the signature.
Note
This does not authenticate the certificate or check its chain, validity, identity, critical extensions, leaf status or permitted key usage.

◆ VerifyDNSName()

ExpectedIdentity StormByte::Crypto::X509::Certificate::VerifyDNSName ( std::string_view expected) const

Checks that the certificate asserts an expected DNS host name.

Parameters
expectedASCII host name supplied by the caller (for example from the connection URL), never taken from this certificate. Internationalized names must already be ASCII A-labels; no IDNA conversion is done.
Returns
Success when a dNSName entry matches, or an error.
Exceptions
StormByte::Safe::AllocationErrorEntry or error storage cannot be allocated.

expected is normalized by dropping exactly one trailing dot and is rejected with IdentityError::InvalidExpectedName when empty, malformed, containing NUL or non-hostname bytes, a wildcard, or ending in an all-digit label (IP literals must use VerifyIPAddress). Matching is a full, ASCII case-insensitive comparison against dNSName entries only. A wildcard entry matches exactly one non-empty leftmost label (*.example.com matches www.example.com, not example.com or a.b.example.com). The common name is never a fallback and DNS names never match iPAddress entries. The extension is validated as in SubjectAltNames before any matching, so a malformed entry fails even when another entry matches; no matching entry yields IdentityError::NoMatch.

Note
This only compares names. It does not verify a chain, validity, key usage or extended key usage and does not authenticate a peer.

◆ VerifyIPAddress()

ExpectedIdentity StormByte::Crypto::X509::Certificate::VerifyIPAddress ( std::span< const std::byte > expected) const

Checks that the certificate asserts an expected IP address.

Parameters
expectedBinary address supplied by the caller: 4 bytes (IPv4) or 16 bytes (IPv6) in network order; any other size is rejected with IdentityError::InvalidExpectedAddress.
Returns
Success when an iPAddress entry has exactly the same bytes, or an error.
Exceptions
StormByte::Safe::AllocationErrorEntry or error storage cannot be allocated.

Comparison is exact over the bytes; there is no textual parsing, no DNS fallback, no wildcard and no IPv4-mapped IPv6 equivalence. Extension validation and errors follow VerifyDNSName.

Note
This only compares addresses; it is not chain or peer authentication.

◆ VerifyTLSPurpose()

ExpectedPurpose StormByte::Crypto::X509::Certificate::VerifyTLSPurpose ( TLSRole role) const

Checks only EKU and KU for a TLS 1.3 certificate signing role.

Parameters
roleServer or Client; other enum values yield UnsupportedRole.
Returns
Success when usage permits the role, or a PurposeError.
Exceptions
StormByte::Safe::AllocationErrorError storage cannot be allocated.

Missing EKU is unrestricted (RFC 5280 §4.2.1.12). Present EKU must explicitly contain serverAuth (1.3.6.1.5.5.7.3.1) for Server or clientAuth (1.3.6.1.5.5.7.3.2) for Client. Under the RFC's permission to require a particular purpose, anyExtendedKeyUsage (2.5.29.37.0) alone does not substitute for either; combined with the explicit purpose it is accepted. Unknown well-formed OIDs and repeated purpose OIDs are allowed but do not grant a role. Every OID is validated before accepting any match, irrespective of the extension's critical flag.

Missing KU is unrestricted; present KU must be a strict DER named BIT STRING with at least one defined bit and digitalSignature set, for both roles (RFC 8446 §4.4.2.2). keyEncipherment or keyAgreement alone never suffices. This leaves Parse and HasKeyUsage unchanged. Errors are checked in order: role, empty certificate, malformed EKU, malformed KU, denied EKU, denied KU.

Note
This is not leaf classification, trust, chain, validity, critical extension processing, signature/key suitability or peer authentication. CA flags are not checked; identity verification remains separate.

◆ Version()

unsigned StormByte::Crypto::X509::Certificate::Version ( ) const
noexcept

Returns the certificate version.

Returns
1, 2 or 3.

◆ RevocationVerifier

friend class RevocationVerifier
friend

Offline CRL/OCSP verification shares parsed certificate state.

◆ TLSPeerVerifier

friend class TLSPeerVerifier
friend

Additive peer composition shares immutable parser state.


The documentation for this class was generated from the following file: