crypto
April 7, 2026 ยท View on GitHub
{#cryptomodule}
crypto
Cryptographic operations; hashing, HMAC, RSA, X509 certificates.
Namespaces
| Name | Description |
|---|---|
crypto | Cryptographic primitives, key helpers, and certificate utilities backed by OpenSSL. |
{#crypto}
crypto
Cryptographic primitives, key helpers, and certificate utilities backed by OpenSSL.
Classes
| Name | Description |
|---|---|
Cipher | Provides symmetric algorithms for encryption and decryption. The algorithms that are available depend on the particular version of OpenSSL that is installed. |
Hash | Incremental cryptographic hash engine wrapping OpenSSL EVP digest functions. |
X509Certificate | RAII wrapper for an OpenSSL X509 certificate with PEM loading and inspection. |
Typedefs
| Return | Name | Description |
|---|---|---|
std::unique_ptr< EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)> | EvpCipherCtxPtr | Owning OpenSSL cipher context handle with automatic EVP_CIPHER_CTX_free. |
std::vector< unsigned char > | ByteVec | Generic storage container for storing cryptographic binary data. |
std::unique_ptr< EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> | EvpMdCtxPtr | Owning OpenSSL digest context handle with automatic EVP_MD_CTX_free. |
::RSA | RSAKey | Alias for the OpenSSL RSA key type, brought into the icy::crypto namespace. |
std::unique_ptr< X509, decltype(&X509_free)> | X509Ptr | RAII pointer alias for OpenSSL X509* values. |
{#evpcipherctxptr}
EvpCipherCtxPtr
std::unique_ptr< EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)> EvpCipherCtxPtr()
Owning OpenSSL cipher context handle with automatic EVP_CIPHER_CTX_free.
{#bytevec}
ByteVec
std::vector< unsigned char > ByteVec()
Generic storage container for storing cryptographic binary data.
{#evpmdctxptr}
EvpMdCtxPtr
std::unique_ptr< EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> EvpMdCtxPtr()
Owning OpenSSL digest context handle with automatic EVP_MD_CTX_free.
{#rsakey}
RSAKey
::RSA RSAKey()
Alias for the OpenSSL RSA key type, brought into the icy::crypto namespace.
Currently a transparent alias for the OpenSSL RSA struct. Use OpenSSL RSA_* functions directly to create, populate, and free RSAKey objects. This alias exists as a stable forward-declaration point; a higher-level RAII wrapper may replace it in a future version.
{#x509ptr}
X509Ptr
std::unique_ptr< X509, decltype(&X509_free)> X509Ptr()
RAII pointer alias for OpenSSL X509* values.
Functions
| Return | Name | Description |
|---|---|---|
std::string | encryptString | Encrypts a string using the specified cipher, key, and IV in a single call. |
std::string | decryptString | Decrypts a string using the specified cipher, key, and IV in a single call. |
void | initializeEngine | Initialize the Crypto library, as well as the underlying OpenSSL libraries. |
void | uninitializeEngine | Uninitializes the Crypto library. |
std::string | hash inline | Computes a hex-encoded digest of a string in a single call. |
std::string | hash inline | Computes a hex-encoded digest of a raw buffer in a single call. |
std::string | checksum inline | Computes the hex-encoded checksum of a file using the given algorithm. |
std::string | computeHMAC | Computes an HMAC-SHA1 message authentication code. |
{#encryptstring}
encryptString
template<typename K, typename I> std::string encryptString(const std::string & algorithm, const std::string & data, const K & key, const I & iv, Cipher::Encoding encoding)
Encrypts a string using the specified cipher, key, and IV in a single call.
Constructs a Cipher, optionally applies key and iv (skipped when empty), then delegates to Cipher::encryptString().
Parameters
-
KKey container type compatible with internal::Raw. -
IIV container type compatible with internal::Raw.
Parameters
-
algorithmOpenSSL cipher name (e.g. "aes-256-cbc"). -
dataPlaintext string to encrypt. -
keyEncryption key; pass an empty container to use a random key. -
ivInitialization vector; pass an empty container to use a random IV. -
encodingTransport encoding for the output (default: Binary).
Returns
Encrypted (and optionally encoded) result as a std::string.
{#decryptstring}
decryptString
template<typename K, typename I> std::string decryptString(const std::string & algorithm, const std::string & data, const K & key, const I & iv, Cipher::Encoding encoding)
Decrypts a string using the specified cipher, key, and IV in a single call.
Constructs a Cipher, optionally applies key and iv (skipped when empty), then delegates to Cipher::decryptString().
Parameters
-
KKey container type compatible with internal::Raw. -
IIV container type compatible with internal::Raw.
Parameters
-
algorithmOpenSSL cipher name (e.g. "aes-256-cbc"). -
dataCiphertext string to decrypt, in the format given byencoding. -
keyDecryption key; pass an empty container to use a random key. -
ivInitialization vector; pass an empty container to use a random IV. -
encodingTransport encoding of the input data (default: Binary).
Returns
Decrypted plaintext as a std::string.
{#initializeengine}
initializeEngine
void initializeEngine()
Initialize the Crypto library, as well as the underlying OpenSSL libraries.
OpenSSL must be initialized before using any classes from the Crypto library. OpenSSL will be initialized automatically through OpenSSL instances held by various Crypto classes (Cipher, Hash, X509Certificate), however it is recommended to call initializeEngine() in any case at application startup.
The Crypto library can be called multiple times; however, for every call to initializeEngine(), a matching call to uninitializeEngine() must be performed.
{#uninitializeengine}
uninitializeEngine
void uninitializeEngine()
Uninitializes the Crypto library.
{#hash-1}
hash
inline
inline std::string hash(const std::string & algorithm, std::string_view data)
Computes a hex-encoded digest of a string in a single call.
Parameters
-
algorithmOpenSSL digest name (e.g. "sha256", "md5"). -
dataInput data to hash.
Returns
Lowercase hex-encoded digest string.
{#hash-2}
hash
inline
inline std::string hash(const std::string & algorithm, const void * data, unsigned length)
Computes a hex-encoded digest of a raw buffer in a single call.
Parameters
-
algorithmOpenSSL digest name (e.g. "sha256", "md5"). -
dataPointer to the input buffer. -
lengthNumber of bytes to hash.
Returns
Lowercase hex-encoded digest string.
{#checksum-1}
checksum
inline
inline std::string checksum(const std::string & algorithm, const std::string & path)
Computes the hex-encoded checksum of a file using the given algorithm.
Reads the file in 4096-byte chunks; suitable for large files.
Parameters
-
algorithmOpenSSL digest name (e.g. "sha256", "md5"). -
pathFilesystem path to the file to hash.
Returns
Lowercase hex-encoded digest string.
Exceptions
std::runtime_errorif the file cannot be opened.
{#computehmac}
computeHMAC
std::string computeHMAC(std::string_view input, std::string_view key)
Computes an HMAC-SHA1 message authentication code.
Uses OpenSSL HMAC with SHA-1 as the underlying digest. The output is a 20-byte raw binary string (not hex-encoded).
Parameters
-
inputData to authenticate. -
keySecret key used for the HMAC computation.
Returns
20-byte raw binary HMAC-SHA1 digest.
Exceptions
std::runtime_errorif OpenSSL returns an unexpected digest length.
{#cipher}
Cipher
#include <icy/crypto/cipher.h>
Provides symmetric algorithms for encryption and decryption. The algorithms that are available depend on the particular version of OpenSSL that is installed.
Public Methods
| Return | Name | Description |
|---|---|---|
Cipher | Constructs a Cipher with a randomly generated key and IV. | |
Cipher | Constructs a Cipher with an explicit key and initialization vector. | |
Cipher | Constructs a Cipher and derives a key and IV from a passphrase. | |
~Cipher | Destroys the Cipher and resets the OpenSSL context. | |
void | initEncryptor | Initializes the cipher context for encryption. |
void | initDecryptor | Initializes the cipher context for decryption. |
ssize_t | update | Processes a block of data through the cipher (encrypt or decrypt). |
ssize_t | update inline | Processes a block of data through the cipher using generic buffer types. |
ssize_t | final | Finalizes the cipher operation and flushes any remaining buffered data. |
ssize_t | final inline | Finalizes the cipher operation using a generic output buffer type. |
ssize_t | encrypt | Encrypts a buffer and writes the result with optional transport encoding. |
ssize_t | encrypt inline | Encrypts data using generic input/output buffer types. |
std::string | encryptString virtual | Encrypts a string and returns the result with optional transport encoding. |
std::string | decryptString virtual | Decrypts a string that was previously encrypted with optional encoding. |
void | encryptStream virtual | Encrypts all data from source and writes the result to sink. |
void | decryptStream virtual | Decrypts all data from source and writes the result to sink. |
void | setKey inline | Sets the encryption key. |
void | setIV inline | Sets the initialization vector (IV). |
int | setPadding | Enables or disables PKCS block padding. |
const ByteVec & | getKey const | Returns the raw encryption key bytes. |
const ByteVec & | getIV const | Returns the raw initialization vector bytes. |
const std::string & | name const | Returns the OpenSSL cipher name this object was constructed with. |
int | blockSize const | Returns the cipher block size in bytes. |
int | keySize const | Returns the required key length in bytes for this cipher. |
int | ivSize const | Returns the required initialization vector length in bytes. |
const EVP_CIPHER * | cipher | Returns the underlying OpenSSL EVP_CIPHER object. |
{#cipher-1}
Cipher
Cipher(const std::string & name)
Constructs a Cipher with a randomly generated key and IV.
Parameters
nameOpenSSL cipher name (e.g. "aes-256-cbc").
Exceptions
std::invalid_argumentif the cipher name is not recognized.
{#cipher-2}
Cipher
Cipher(const std::string & name, const ByteVec & key, const ByteVec & iv)
Constructs a Cipher with an explicit key and initialization vector.
Parameters
-
nameOpenSSL cipher name (e.g. "aes-256-cbc"). -
keyEncryption key; must match the cipher's required key length. -
ivInitialization vector; must match the cipher's IV length.
Exceptions
std::invalid_argumentif the cipher name is not recognized.
{#cipher-3}
Cipher
Cipher(const std::string & name, std::string_view passphrase, std::string_view salt, int iterationCount)
Constructs a Cipher and derives a key and IV from a passphrase.
Uses EVP_BytesToKey with SHA-256 to derive the key material.
Parameters
-
nameOpenSSL cipher name (e.g. "aes-256-cbc"). -
passphraseSecret passphrase for key derivation. -
saltOptional salt string; empty string means no salt. Values longer than 8 bytes are folded via XOR. -
iterationCountNumber of key-derivation iterations.
Exceptions
std::invalid_argumentif the cipher name is not recognized.
{#cipher-4}
~Cipher
~Cipher()
Destroys the Cipher and resets the OpenSSL context.
{#initencryptor}
initEncryptor
void initEncryptor()
Initializes the cipher context for encryption.
Must be called before using update() and final() in encrypt mode. Calling this resets any prior context state.
{#initdecryptor}
initDecryptor
void initDecryptor()
Initializes the cipher context for decryption.
Must be called before using update() and final() in decrypt mode. Calling this resets any prior context state.
{#update-7}
update
ssize_t update(const unsigned char * input, size_t inputLength, unsigned char * output, size_t outputLength)
Processes a block of data through the cipher (encrypt or decrypt).
Hand consecutive blocks of data to this method for streaming operation. The output buffer must be at least inputLength + [blockSize()](#blocksize) - 1 bytes. After all input is processed, call final() to flush any remaining buffered data from the cipher context.
Parameters
-
inputPointer to the input data buffer. -
inputLengthNumber of bytes to process frominput. -
outputPointer to the output buffer. -
outputLengthSize of the output buffer in bytes.
Returns
Number of bytes written to output.
Exceptions
std::runtime_errorif the output buffer is too small.
{#update-8}
update
inline
template<typename I, typename O> inline ssize_t update(const I & input, O & output)
Processes a block of data through the cipher using generic buffer types.
Convenience wrapper around update(const unsigned char*, size_t, unsigned char*, size_t). Accepts any type supported by internal::Raw.
Parameters
-
inputInput buffer (std::string, ByteVec, etc.). -
outputOutput buffer; must be large enough for the result.
Returns
Number of bytes written to output.
{#final}
final
ssize_t final(unsigned char * output, size_t length)
Finalizes the cipher operation and flushes any remaining buffered data.
Must be called after the last update() call to retrieve any trailing cipher block. Further calls to update() or final() after this point produce undefined results; call initEncryptor() / initDecryptor() to reset. The output buffer must be at least blockSize() bytes.
See EVP_CipherFinal_ex for further information.
Parameters
-
outputPointer to the output buffer; must be at least blockSize() bytes. -
lengthSize of the output buffer in bytes.
Returns
Number of bytes written to output.
Exceptions
std::runtime_errorif the output buffer is smaller than blockSize().
{#final-1}
final
inline
template<typename O> inline ssize_t final(O & output)
Finalizes the cipher operation using a generic output buffer type.
Convenience wrapper around final(unsigned char*, size_t). Accepts any type supported by internal::Raw.
Parameters
outputOutput buffer; must hold at least blockSize() bytes.
Returns
Number of bytes written to output.
{#encrypt}
encrypt
ssize_t encrypt(const unsigned char * inbuf, size_t inlen, unsigned char * outbuf, size_t outlen, Encoding encoding)
Encrypts a buffer and writes the result with optional transport encoding.
Calls initEncryptor(), update(), and final() internally; the cipher does not need to be pre-initialized. The output buffer must be large enough to hold the encrypted and encoded result.
Parameters
-
inbufPointer to the plaintext input buffer. -
inlenNumber of bytes to encrypt frominbuf. -
outbufPointer to the output buffer. -
outlenSize of the output buffer in bytes. -
encodingTransport encoding applied to the ciphertext (default: Binary).
Returns
Total number of bytes written to outbuf.
{#encrypt-1}
encrypt
inline
template<typename I, typename O> inline ssize_t encrypt(const I & input, O & output, Encoding encoding)
Encrypts data using generic input/output buffer types.
Convenience wrapper around encrypt(const unsigned char*, size_t, unsigned char*, size_t, Encoding). Accepts any type supported by internal::Raw.
Parameters
-
inputInput buffer containing plaintext. -
outputOutput buffer; must be large enough for the result. -
encodingTransport encoding applied to the ciphertext (default: Binary).
Returns
Total number of bytes written to output.
{#encryptstring-1}
encryptString
virtual
virtual std::string encryptString(const std::string & str, Encoding encoding)
Encrypts a string and returns the result with optional transport encoding.
Internally streams through encryptStream(); the cipher is re-initialized on each call.
Parameters
-
strPlaintext string to encrypt. -
encodingTransport encoding for the output (default: Binary).
Returns
Encrypted (and optionally encoded) result as a std::string.
{#decryptstring-1}
decryptString
virtual
virtual std::string decryptString(const std::string & str, Encoding encoding)
Decrypts a string that was previously encrypted with optional encoding.
Internally streams through decryptStream(); the cipher is re-initialized on each call.
Parameters
-
strCiphertext string to decrypt, in the format given byencoding. -
encodingTransport encoding of the input (default: Binary).
Returns
Decrypted plaintext as a std::string.
{#encryptstream}
encryptStream
virtual
virtual void encryptStream(std::istream & source, std::ostream & sink, Encoding encoding)
Encrypts all data from source and writes the result to sink.
Reads in chunks of [blockSize()](#blocksize) * 128 bytes. Calls initEncryptor() internally; no prior initialization is required.
Parameters
-
sourceInput stream containing plaintext. -
sinkOutput stream to receive the encrypted (and encoded) data. -
encodingTransport encoding applied to the output (default: Binary).
{#decryptstream}
decryptStream
virtual
virtual void decryptStream(std::istream & source, std::ostream & sink, Encoding encoding)
Decrypts all data from source and writes the result to sink.
Reads in chunks of [blockSize()](#blocksize) * 128 bytes. Calls initDecryptor() internally; no prior initialization is required.
Parameters
-
sourceInput stream containing ciphertext (in the given encoding). -
sinkOutput stream to receive the decrypted plaintext. -
encodingTransport encoding of the input data (default: Binary).
{#setkey-1}
setKey
inline
template<typename T> inline void setKey(const T & key)
Sets the encryption key.
Parameters
keyContainer whose size must exactly match keySize().
Exceptions
std::logic_errorif key.size() != keySize().
{#setiv}
setIV
inline
template<typename T> inline void setIV(const T & iv)
Sets the initialization vector (IV).
Parameters
ivContainer whose size must exactly match ivSize().
Exceptions
std::logic_errorif iv.size() != ivSize().
{#setpadding}
setPadding
int setPadding(int padding)
Enables or disables PKCS block padding.
By default, encryption pads input to a block boundary and decryption strips and validates the padding. If padding is zero, no padding is applied; the total data length must then be an exact multiple of blockSize() or the operation will fail.
See EVP_CIPHER_CTX_set_padding for further information.
Parameters
paddingNon-zero to enable padding (default), zero to disable.
Returns
The return value from EVP_CIPHER_CTX_set_padding.
{#getkey}
getKey
const
const ByteVec & getKey() const
Returns the raw encryption key bytes.
Returns
Reference to the internal key byte vector.
{#getiv}
getIV
const
const ByteVec & getIV() const
Returns the raw initialization vector bytes.
Returns
Reference to the internal IV byte vector.
{#name-11}
name
const
const std::string & name() const
Returns the OpenSSL cipher name this object was constructed with.
Returns
Cipher name string (e.g. "aes-256-cbc").
{#blocksize}
blockSize
const
int blockSize() const
Returns the cipher block size in bytes.
Returns
Block size as reported by EVP_CIPHER_block_size.
{#keysize}
keySize
const
int keySize() const
Returns the required key length in bytes for this cipher.
Returns
Key length as reported by EVP_CIPHER_key_length.
{#ivsize}
ivSize
const
int ivSize() const
Returns the required initialization vector length in bytes.
Returns
IV length as reported by EVP_CIPHER_iv_length.
{#cipher-5}
cipher
const EVP_CIPHER * cipher()
Returns the underlying OpenSSL EVP_CIPHER object.
Returns
Pointer to the OpenSSL cipher descriptor; valid for the lifetime of this Cipher object.
Protected Attributes
| Return | Name | Description |
|---|---|---|
bool | _initialized | |
bool | _encrypt | |
const EVP_CIPHER * | _cipher | |
EvpCipherCtxPtr | _ctx | |
std::string | _name | |
ByteVec | _key | |
ByteVec | _iv |
{#_initialized-2}
_initialized
bool _initialized
{#_encrypt}
_encrypt
bool _encrypt
{#_cipher}
_cipher
const EVP_CIPHER * _cipher
{#_ctx}
_ctx
EvpCipherCtxPtr _ctx
{#_name-2}
_name
std::string _name
{#_key-2}
_key
ByteVec _key
{#_iv}
_iv
ByteVec _iv
Protected Methods
| Return | Name | Description |
|---|---|---|
Cipher | Deleted constructor. | |
Cipher | Deleted constructor. | |
Cipher | Deleted constructor. | |
void | generateKey | Derives and sets the key and IV from a passphrase using EVP_BytesToKey. |
void | setRandomKey | Fills the key buffer with cryptographically random bytes. |
void | setRandomIV | Fills the IV buffer with cryptographically random bytes. |
void | init | Initializes or resets the OpenSSL cipher context for the given direction. |
{#cipher-6}
Cipher
Cipher() = delete
Deleted constructor.
{#cipher-7}
Cipher
Cipher(const Cipher &) = delete
Deleted constructor.
{#cipher-8}
Cipher
Cipher(Cipher &&) = delete
Deleted constructor.
{#generatekey}
generateKey
void generateKey(std::string_view passphrase, std::string_view salt, int iterationCount)
Derives and sets the key and IV from a passphrase using EVP_BytesToKey.
Uses SHA-256 as the digest. Salt values longer than 8 bytes are folded by XOR into an 8-byte array as required by OpenSSL.
Parameters
-
passphraseSecret passphrase for key derivation. -
saltSalt string (may be empty for no salt). -
iterationCountNumber of digest iterations.
{#setrandomkey}
setRandomKey
void setRandomKey()
Fills the key buffer with cryptographically random bytes.
{#setrandomiv}
setRandomIV
void setRandomIV()
Fills the IV buffer with cryptographically random bytes.
{#init-9}
init
void init(bool encrypt)
Initializes or resets the OpenSSL cipher context for the given direction.
Parameters
encrypttrue to initialize for encryption, false for decryption.
Public Types
| Name | Description |
|---|---|
Encoding | Transport encoding to use for encrypt() and decrypt(). |
{#encoding-1}
Encoding
enum Encoding
Transport encoding to use for encrypt() and decrypt().
| Value | Description |
|---|---|
Binary | Plain binary output. |
Base64 | Base64-encoded output. |
BinHex | BinHex-encoded output. |
Base64_NoLF | Base64-encoded output, no linefeeds. |
BinHex_NoLF | BinHex-encoded output, no linefeeds. |
{#hash-3}
Hash
#include <icy/crypto/hash.h>
Incremental cryptographic hash engine wrapping OpenSSL EVP digest functions.
Construct with an algorithm name recognized by OpenSSL (e.g. "sha256", "md5"). Feed data with one or more calls to update(), then call digest() or digestStr() to finalize and retrieve the result. Call reset() to reuse the engine for a new computation without reallocating the context.
Public Methods
| Return | Name | Description |
|---|---|---|
Hash | Constructs a Hash engine for the given algorithm. | |
~Hash | Destroys the Hash engine and releases OpenSSL resources. | |
void | update | Feeds a single character into the digest computation. |
void | update | Feeds a string view into the digest computation. |
void | update | Feeds a raw memory buffer into the digest computation. |
const ByteVec & | digest | Finalizes the digest computation and returns the raw binary result. |
std::string | digestStr | Finalizes the digest computation and returns the result as a raw binary string (not hex-encoded). Use icy::hex::encode() on digest() if you need a printable representation. |
void | reset | Resets the digest context and clears the cached result, allowing the engine to be reused for a new computation with the same algorithm. |
const std::string & | algorithm const | Returns the algorithm name this engine was constructed with. |
{#hash-4}
Hash
Hash(const std::string & algorithm)
Constructs a Hash engine for the given algorithm.
Parameters
algorithmOpenSSL digest name (e.g. "sha256", "sha1", "md5").
Exceptions
std::runtime_errorif the algorithm is not recognized by OpenSSL.
{#hash-5}
~Hash
~Hash()
Destroys the Hash engine and releases OpenSSL resources.
{#update-9}
update
void update(char data)
Feeds a single character into the digest computation.
Parameters
dataThe byte to hash.
{#update-10}
update
void update(std::string_view data)
Feeds a string view into the digest computation.
Parameters
dataThe data to hash.
{#update-11}
update
void update(const void * data, size_t length)
Feeds a raw memory buffer into the digest computation.
This method may be called multiple times for streaming large inputs.
Parameters
-
dataPointer to the input buffer. -
lengthNumber of bytes to hash fromdata.
{#digest}
digest
const ByteVec & digest()
Finalizes the digest computation and returns the raw binary result.
The result is computed on the first call and cached; subsequent calls return the same value without recomputing. Call reset() before reusing the engine for a new computation.
Returns
Reference to the internal byte vector containing the digest.
{#digeststr}
digestStr
std::string digestStr()
Finalizes the digest computation and returns the result as a raw binary string (not hex-encoded). Use icy::hex::encode() on digest() if you need a printable representation.
Returns
Binary digest as a std::string.
{#reset-13}
reset
void reset()
Resets the digest context and clears the cached result, allowing the engine to be reused for a new computation with the same algorithm.
{#algorithm}
algorithm
const
const std::string & algorithm() const
Returns the algorithm name this engine was constructed with.
Returns
OpenSSL digest name string (e.g. "sha256").
Protected Attributes
| Return | Name | Description |
|---|---|---|
EvpMdCtxPtr | _ctx | |
const EVP_MD * | _md | |
crypto::ByteVec | _digest | |
std::string | _algorithm |
{#_ctx-1}
_ctx
EvpMdCtxPtr _ctx
{#_md}
_md
const EVP_MD * _md
{#_digest}
_digest
crypto::ByteVec _digest
{#_algorithm}
_algorithm
std::string _algorithm
{#x509certificate}
X509Certificate
#include <icy/crypto/x509certificate.h>
RAII wrapper for an OpenSSL X509 certificate with PEM loading and inspection.
Public Methods
| Return | Name | Description |
|---|---|---|
X509Certificate explicit | Constructs an X509Certificate by parsing a PEM-encoded certificate from memory. | |
X509Certificate explicit | Constructs an X509Certificate by reading a PEM-encoded certificate from a file. | |
X509Certificate explicit | Constructs an X509Certificate taking ownership of an existing OpenSSL X509 object. | |
X509Certificate | Constructs an X509Certificate from an existing OpenSSL X509 object, optionally sharing ownership via reference count increment. | |
X509Certificate | Copy-constructs an X509Certificate by duplicating the underlying X509 object. | |
X509Certificate | Move-constructs an X509Certificate, transferring ownership from cert. | |
X509Certificate & | operator= | Copy-assigns a certificate, duplicating the underlying X509 object. |
X509Certificate & | operator= | Move-assigns a certificate, transferring ownership from cert. |
void | swap | Swaps this certificate with cert. |
~X509Certificate | Destroys the X509Certificate and releases the underlying OpenSSL X509 object. | |
const std::string & | issuerName const | Returns the full distinguished name of the certificate issuer. |
std::string | issuerName const | Extracts a single field from the certificate issuer's distinguished name. |
const std::string & | subjectName const | Returns the full distinguished name of the certificate subject. |
std::string | subjectName const | Extracts a single field from the certificate subject's distinguished name. |
std::string | commonName const | Returns the common name (CN) from the certificate subject. |
void | extractNames const | Extracts the common name and the set of Subject Alternative Name (SAN) DNS entries from the certificate. |
DateTime | validFrom const | Returns the date and time from which the certificate is valid. |
DateTime | expiresOn const | Returns the date and time at which the certificate expires. |
void | save const | Writes the certificate in PEM format to an output stream. |
void | save const | Writes the certificate in PEM format to a file. |
bool | issuedBy const | Verifies whether this certificate was signed by the given issuer. |
const X509 * | certificate const | Returns a const pointer to the underlying OpenSSL X509 object. |
X509 * | certificate | Returns a mutable pointer to the underlying OpenSSL X509 object. |
{#x509certificate-1}
X509Certificate
explicit
explicit X509Certificate(const char * data, size_t length)
Constructs an X509Certificate by parsing a PEM-encoded certificate from memory.
Parameters
-
dataPointer to a buffer containing the PEM-encoded certificate. -
lengthNumber of bytes indata.
Exceptions
std::runtime_errorif the BIO cannot be created or PEM parsing fails.
{#x509certificate-2}
X509Certificate
explicit
explicit X509Certificate(const std::string & path)
Constructs an X509Certificate by reading a PEM-encoded certificate from a file.
Parameters
pathFilesystem path to the PEM certificate file.
Exceptions
std::runtime_errorif the file cannot be opened or PEM parsing fails.
{#x509certificate-3}
X509Certificate
explicit
explicit X509Certificate(X509 * pCert)
Constructs an X509Certificate taking ownership of an existing OpenSSL X509 object.
Parameters
pCertNon-null pointer to an OpenSSL X509 certificate. This object takes ownership and will call X509_free on destruction.
Exceptions
std::runtime_errorifpCertis null.
{#x509certificate-4}
X509Certificate
X509Certificate(X509 * pCert, bool shared)
Constructs an X509Certificate from an existing OpenSSL X509 object, optionally sharing ownership via reference count increment.
Parameters
-
pCertNon-null pointer to an OpenSSL X509 certificate. Ownership is always taken (X509_free called on destruction). -
sharedIf true, increments the certificate's reference count via X509_up_ref before taking ownership, so the original pointer remains valid after this object is destroyed.
Exceptions
std::runtime_errorifpCertis null.
{#x509certificate-5}
X509Certificate
X509Certificate(const X509Certificate & cert)
Copy-constructs an X509Certificate by duplicating the underlying X509 object.
Parameters
certThe certificate to copy.
{#x509certificate-6}
X509Certificate
X509Certificate(X509Certificate && cert) noexcept
Move-constructs an X509Certificate, transferring ownership from cert.
Parameters
certThe certificate to move from; left in a valid but empty state.
{#operator-25}
operator=
X509Certificate & operator=(const X509Certificate & cert)
Copy-assigns a certificate, duplicating the underlying X509 object.
Parameters
certThe certificate to copy.
Returns
Reference to this object.
{#operator-26}
operator=
X509Certificate & operator=(X509Certificate && cert) noexcept
Move-assigns a certificate, transferring ownership from cert.
Parameters
certThe certificate to move from; left in a valid but empty state.
Returns
Reference to this object.
{#swap-6}
swap
void swap(X509Certificate & cert)
Swaps this certificate with cert.
Parameters
certThe certificate to swap with.
{#x509certificate-7}
~X509Certificate
~X509Certificate()
Destroys the X509Certificate and releases the underlying OpenSSL X509 object.
{#issuername}
issuerName
const
const std::string & issuerName() const
Returns the full distinguished name of the certificate issuer.
Returns
One-line string representation produced by X509_NAME_oneline.
{#issuername-1}
issuerName
const
std::string issuerName(NID nid) const
Extracts a single field from the certificate issuer's distinguished name.
Parameters
nidThe field to extract (e.g. NID_COMMON_NAME).
Returns
Field value, or an empty string if the field is absent.
{#subjectname}
subjectName
const
const std::string & subjectName() const
Returns the full distinguished name of the certificate subject.
Returns
One-line string representation produced by X509_NAME_oneline.
{#subjectname-1}
subjectName
const
std::string subjectName(NID nid) const
Extracts a single field from the certificate subject's distinguished name.
Parameters
nidThe field to extract (e.g. NID_ORGANIZATION_NAME).
Returns
Field value, or an empty string if the field is absent.
{#commonname}
commonName
const
std::string commonName() const
Returns the common name (CN) from the certificate subject.
Convenience wrapper for subjectName(NID_COMMON_NAME).
Returns
Common name string, or empty if absent.
{#extractnames}
extractNames
const
void extractNames(std::string & commonName, std::set< std::string > & domainNames) const
Extracts the common name and the set of Subject Alternative Name (SAN) DNS entries from the certificate.
If no SAN DNS entries are present and the common name is non-empty, the common name is added to domainNames as a fallback.
Parameters
-
commonNameReceives the certificate's common name. -
domainNamesReceives all DNS SAN entries (cleared before population).
{#validfrom}
validFrom
const
DateTime validFrom() const
Returns the date and time from which the certificate is valid.
Parsed from the X509 notBefore field.
Returns
UTC DateTime representing the start of the validity period.
{#expireson}
expiresOn
const
DateTime expiresOn() const
Returns the date and time at which the certificate expires.
Parsed from the X509 notAfter field.
Returns
UTC DateTime representing the end of the validity period.
{#save-1}
save
const
void save(std::ostream & stream) const
Writes the certificate in PEM format to an output stream.
Parameters
streamDestination stream to write to.
Exceptions
std::runtime_errorif the BIO cannot be created or write fails.
{#save-2}
save
const
void save(const std::string & path) const
Writes the certificate in PEM format to a file.
Parameters
pathFilesystem path of the output file (created or truncated).
Exceptions
std::runtime_errorif the file cannot be opened or write fails.
{#issuedby}
issuedBy
const
bool issuedBy(const X509Certificate & issuerCertificate) const
Verifies whether this certificate was signed by the given issuer.
Extracts the public key from issuerCertificate and calls X509_verify. Use this to validate links in a certificate chain.
Parameters
issuerCertificateThe certificate of the purported issuer.
Returns
true if this certificate's signature verifies against the issuer's public key, false otherwise.
Exceptions
std::invalid_argumentif the issuer certificate has no public key.
{#certificate-1}
certificate
const
const X509 * certificate() const
Returns a const pointer to the underlying OpenSSL X509 object.
Returns
Pointer valid for the lifetime of this X509Certificate.
{#certificate-2}
certificate
X509 * certificate()
Returns a mutable pointer to the underlying OpenSSL X509 object.
Returns
Pointer valid for the lifetime of this X509Certificate.
Protected Methods
| Return | Name | Description |
|---|---|---|
void | load | Parses a PEM-encoded certificate from a memory buffer and stores it. |
void | load | Reads a PEM-encoded certificate from a file and stores it. |
void | init | Populates _issuerName and _subjectName from the loaded certificate. |
{#load-2}
load
void load(const char * data, size_t length)
Parses a PEM-encoded certificate from a memory buffer and stores it.
Parameters
-
dataPointer to PEM data. -
lengthNumber of bytes indata.
Exceptions
-
std::logic_errorif a certificate is already loaded. -
std::runtime_errorif BIO creation or PEM parsing fails.
{#load-3}
load
void load(const std::string & path)
Reads a PEM-encoded certificate from a file and stores it.
Parameters
pathFilesystem path to the PEM certificate file.
Exceptions
-
std::logic_errorif a certificate is already loaded. -
std::runtime_errorif the file cannot be opened or PEM parsing fails.
{#init-10}
init
void init()
Populates _issuerName and _subjectName from the loaded certificate.
Called after each successful load or construction from an X509 pointer.
Public Types
| Name | Description |
|---|---|
NID | Name identifier for extracting fields from a certificate's distinguished name. |
{#nid}
NID
enum NID
Name identifier for extracting fields from a certificate's distinguished name.
Values correspond to OpenSSL NID constants used with X509_NAME_get_text_by_NID.
| Value | Description |
|---|---|
NID_COMMON_NAME | Common name (CN field). |
NID_COUNTRY | Country code (C field). |
NID_LOCALITY_NAME | Locality / city (L field). |
NID_STATE_OR_PROVINCE | State or province (ST field). |
NID_ORGANIZATION_NAME | Organization name (O field). |
NID_ORGANIZATION_UNIT_NAME | Organizational unit (OU field). |
Private Attributes
| Return | Name | Description |
|---|---|---|
std::string | _issuerName | |
std::string | _subjectName | |
X509Ptr | _certificate |
{#_issuername}
_issuerName
std::string _issuerName
{#_subjectname}
_subjectName
std::string _subjectName
{#_certificate}
_certificate
X509Ptr _certificate