cryptoprovider_web_logo

CryptoProvider C++ library

v1.0.0

Table of contents

Overview

CryptoProvider is a universal, high-performance C++17 cryptographic library that provides a unified, OpenSSL-like interface across Windows and Linux platforms with automatic backend selection:

  1. Windows: Uses native Windows CNG (Cryptography Next Generation) (bcrypt.h / bcrypt.lib). Reports FIPS mode while the Windows FIPS policy is on (BCryptGetFipsAlgorithmMode), and refuses MD5 then.
  2. Linux with OpenSSL: Uses installed OpenSSL 3.x via a private OSSL_LIB_CTX (FIPS and standard providers). If FIPS mode is enabled on the system (/proc/sys/crypto/fips_enabled) or requested by the application, it loads the FIPS provider and reports FIPS only when the context proves enforcement (SHA2-256 resolves, MD5 does not).
  3. Linux without OpenSSL: Automatically compiles and uses built-in, standalone C++ implementations of all required cryptographic algorithms (MD5, SHA-1, SHA-256, SHA-384, SHA-512, AES-128/256-CTR, AES-128/256-CBC, AES-128/256-GCM, HMAC, PBKDF2, HKDF, /dev/urandom CSPRNG).
  4. Physical Exclusion for Certification: When compiled on Windows or on Linux with OpenSSL, the standalone custom algorithm source files are completely and physically excluded from compilation and object linking via CMake target source filtering and preprocessor guards. This simplifies FIPS and cybersecurity certification by guaranteeing that uncertified fallback code is not present in binary artifacts.

The library implements cryptographic operations required by secure media and network services:

  • Digests: Incremental streaming and one-shot MD5, SHA-1, SHA-256, SHA-384, SHA-512.
  • Symmetric Ciphers: AES-128-CTR (for SRTP encryption per RFC 3711), AES-128-CBC, AES-256-CBC with PKCS#7 padding.
  • Authenticated Encryption (AEAD): AES-128-GCM and AES-256-GCM with automated or explicit 12-byte nonces and 16-byte authentication tags.
  • Message Authentication: HMAC with SHA-1 and SHA-256 (streaming and one-shot).
  • Key Derivation (KDF): PBKDF2-HMAC-SHA256 / SHA1 with NIST SP 800-132 bounds enforcement, and HKDF (RFC 5869 extract-and-expand).
  • CSPRNG: Cryptographically secure random bytes, random 32-bit and 16-bit integers, random hex strings, and RFC 4122 Version 4 UUIDs.
  • Encoding & Utilities: Strict RFC 4648 Base64 encoding/decoding, lower-case Hexadecimal conversion, constant-time memory comparison (constantTimeEquals), and volatile memory wiping (SecureErase).

The library uses C++17 standard, and has zero external dependencies on Windows.

Versions

Table 1 - Library versions.

Version Release date What’s new
1.0.0 29.09.2026 Initial release with CNG, OpenSSL, and Standalone Custom backends.

Library files

The library follows a strict encapsulation layout where client applications only interact with a single universal public header that includes only standard C++ headers (<cstddef>, <cstdint>, <string>, <vector>). All implementation files and platform backends are completely hidden inside the Impl directory.

The repository structure is shown below:

CMakeLists.txt ---------------- Root CMake file of the project.
static ------------------------ Documentation assets (web logo).
src --------------------------- Library source code folder.
    CMakeLists.txt ------------ Library target configuration with recursive file globbing.
    CryptoProvider.h ---------- PUBLIC header: unified interface (only system C++ includes).
    CryptoProvider.cpp -------- Library lifecycle and provider implementation.
    CryptoProviderVersion.h --- Generated version header.
    CryptoProviderVersion.h.in  Version template.
    Impl ---------------------- Internal implementation folder (hidden from clients).
        CryptoBackend.h ------- Internal backend abstraction interface.
        Aead.cpp -------------- AEAD AES-GCM implementation.
        Base64.cpp ------------ RFC 4648 Base64 and Hexadecimal codec.
        Cipher.cpp ------------ Symmetric cipher implementation (AES-CTR, AES-CBC).
        Digest.cpp ------------ Message digest implementation.
        Hmac.cpp -------------- Keyed-hash message authentication code implementation.
        Kdf.cpp --------------- PBKDF2 and HKDF key derivation implementation.
        Random.cpp ------------ Cryptographically secure pseudo-random generator.
        SecureErase.cpp ------- Volatile memory zeroing implementation.
        Cng ------------------- Windows CNG (bcrypt) native backend.
            CngBackend.h ------ CNG backend header.
            CngBackend.cpp ---- CNG backend implementation.
        OpenSsl --------------- Linux OpenSSL 3.x backend.
            OpenSslBackend.h -- OpenSSL backend header.
            OpenSslBackend.cpp  OpenSSL backend implementation.
        Custom ---------------- Standalone custom cryptographic implementations.
            CustomAes.h ------- Standalone AES-128/256 cipher header.
            CustomAes.cpp ----- Standalone AES-128/256 cipher implementation.
            CustomGcm.h ------- Standalone GCM mode header.
            CustomGcm.cpp ----- Standalone GCM mode implementation.
            CustomMd5.h ------- Standalone MD5 digest header.
            CustomMd5.cpp ----- Standalone MD5 digest implementation.
            CustomSha1.h ------ Standalone SHA-1 digest header.
            CustomSha1.cpp ---- Standalone SHA-1 digest implementation.
            CustomSha256.h ---- Standalone SHA-256/384 digest header.
            CustomSha256.cpp -- Standalone SHA-256/384 digest implementation.
            CustomSha512.h ---- Standalone SHA-512 digest header.
            CustomSha512.cpp -- Standalone SHA-512 digest implementation.
            CustomBackend.h --- Standalone custom backend header.
            CustomBackend.cpp - Standalone custom backend implementation.
test -------------------------- Automated unit and NIST/RFC test suite.
    CMakeLists.txt ------------ Test application CMake configuration.
    main.cpp ------------------ 100/100 automated test vectors.
example ----------------------- Standalone runnable example application.
    CMakeLists.txt ------------ Example application CMake configuration.
    main.cpp ------------------ Example usage source code.

Table 2 - Library files.

File Description
CryptoProvider.h Single universal public header. Includes only standard C++ headers.

CryptoProvider class description

CryptoProvider class declaration

CryptoProvider class provides static methods to configure and inspect the cryptographic engine.

namespace cr::crypto
{

class CryptoProvider
{
public:

    static std::string getVersion();

    static bool init(Mode mode = Mode::Standard);

    static bool isReady();

    static Mode requestedMode();

    static bool isFipsActive();

    static bool isFipsAvailable();

    static bool isAllowed(Algo algo);

    static bool isAllowed(Algo algo, Mode mode);

    static std::string lastError();

    static void setLastError(const std::string& error);

    static bool constantTimeEquals(const std::string& a, const std::string& b);

    static bool constantTimeEquals(const void* a, const void* b, size_t size);
};

}

getVersion method

The getVersion() method returns the library version string without initializing cryptography. Method declaration:

static std::string getVersion();

Returns: Library version string in format "Major.Minor.Patch".

Example:

std::cout << "CryptoProvider version: " << cr::crypto::CryptoProvider::getVersion() << std::endl;

init method

The init(…) method initializes the active cryptographic backend for the specified operational mode (Mode::Standard or Mode::Fips). If the host operating system enforces FIPS 140-3 policy, Mode::Fips is selected automatically. Method declaration:

static bool init(Mode mode = Mode::Standard);
Parameter Value
mode Target operational mode (Mode::Standard or Mode::Fips). Default is Mode::Standard.

Returns: TRUE if initialized successfully, or FALSE on failure (e.g. FIPS mode requested on a system without FIPS support).

Example:

bool ok = cr::crypto::CryptoProvider::init(cr::crypto::Mode::Standard);
if (!ok)
{
    std::cerr << "Initialization failed: " << cr::crypto::CryptoProvider::lastError() << std::endl;
}

isReady method

The isReady() method checks whether the underlying cryptographic provider has been successfully initialized and is ready for use. Method declaration:

static bool isReady();

Returns: TRUE if the backend is initialized and ready, or FALSE otherwise.

Example:

if (cr::crypto::CryptoProvider::isReady())
{
    // Backend is operational
}

requestedMode method

The requestedMode() method returns the operational mode established by the last successful init call. Method declaration:

static Mode requestedMode();

Returns: The established Mode enum value (Mode::Standard or Mode::Fips).

Example:

cr::crypto::Mode mode = cr::crypto::CryptoProvider::requestedMode();

isFipsActive method

The isFipsActive() method reports whether FIPS 140-3 compliance policy is actively enforced (either because Mode::Fips was selected or the host operating system has FIPS mode enabled). Method declaration:

static bool isFipsActive();

Returns: TRUE if FIPS 140-3 policy is actively enforced, or FALSE otherwise.

Example:

if (cr::crypto::CryptoProvider::isFipsActive())
{
    std::cout << "FIPS 140-3 mode is active." << std::endl;
}

isFipsAvailable method

The isFipsAvailable() method checks whether FIPS 140-3 validation mode is supported by the host operating system or installed cryptographic libraries. Method declaration:

static bool isFipsAvailable();

Returns: TRUE if FIPS 140-3 mode is available on the system, or FALSE otherwise.

Example:

bool canFips = cr::crypto::CryptoProvider::isFipsAvailable();

isAllowed method

The isAllowed(…) method checks whether a specific cryptographic algorithm is permitted under the current operational mode or a specified mode. In FIPS mode, unapproved algorithms (such as MD5) return false. Method declaration:

static bool isAllowed(Algo algo);
static bool isAllowed(Algo algo, Mode mode);
Parameter Value
algo Algorithm to check (cr::crypto::Algo).
mode Operational mode (Mode::Standard or Mode::Fips). If omitted, current active mode is used.

Returns: TRUE if the algorithm is permitted under the mode, or FALSE otherwise.

Example:

bool md5Allowed = cr::crypto::CryptoProvider::isAllowed(cr::crypto::Algo::Md5);

lastError method

The lastError() method returns the descriptive text of the last failure encountered by the cryptographic engine. Method declaration:

static std::string lastError();

Returns: String describing the last error, or empty string if no error occurred.

Example:

std::string err = cr::crypto::CryptoProvider::lastError();

setLastError method

The setLastError(…) method stores a descriptive error text. Method declaration:

static void setLastError(const std::string& error);
Parameter Value
error Description text to store.

Returns: None.

Example:

cr::crypto::CryptoProvider::setLastError("Invalid parameter length");

constantTimeEquals method

The constantTimeEquals(…) method performs constant-time byte-by-byte comparison of two buffers or strings. It prevents timing side-channel attacks on authentication tokens, HMAC tags, and secret keys. Method declaration:

static bool constantTimeEquals(const std::string& a, const std::string& b);
static bool constantTimeEquals(const void* a, const void* b, size_t size);
Parameter Value
a Pointer to first memory buffer, or first string.
b Pointer to second memory buffer, or second string.
size Number of bytes to compare.

Returns: TRUE if both buffers or strings are identical in constant time, or FALSE otherwise.

Example:

bool match = cr::crypto::CryptoProvider::constantTimeEquals(tagA.data(), tagB.data(), 16);

Digest class description

Digest class declaration

Digest class provides incremental streaming and one-shot message hashing modeled after OpenSSL’s EVP_MD_CTX.

namespace cr::crypto
{

class Digest
{
public:

    explicit Digest(Algo algo);

    ~Digest();

    bool init(Algo algo);

    bool isValid() const;

    bool update(const void* data, size_t size);

    bool update(const std::string& text);

    bool finish(std::vector<uint8_t>& digest);

    bool finalize(std::vector<uint8_t>& digest);

    std::vector<uint8_t> finalize();

    std::string finalizeHex();

    bool reset();

    std::string lastError() const;

    static size_t digestSize(Algo algo);

    static bool hash(Algo algo, const void* data, size_t size,
                     std::vector<uint8_t>& digest);

    static std::string hashHex(Algo algo, const std::string& text);

    static std::string sha1Hex(const std::string& in);

    static std::string sha256Hex(const std::string& in);

    static std::string sha384Hex(const std::string& in);

    static std::string sha512Hex(const std::string& in);

    static std::string md5Hex(const std::string& in);
};

}

Digest constructor

The Digest constructor creates and initializes a digest calculator for the specified algorithm. Method declaration:

explicit Digest(Algo algo);
Parameter Value
algo Digest algorithm (Algo::Md5, Algo::Sha1, Algo::Sha256, Algo::Sha384, Algo::Sha512).

Example:

cr::crypto::Digest md(cr::crypto::Algo::Sha256);

Digest init method

The init(…) method reinitializes the digest calculator with a new algorithm. Method declaration:

bool init(Algo algo);
Parameter Value
algo Digest algorithm to initialize.

Returns: TRUE if initialized successfully, or FALSE on failure (e.g. unapproved algorithm in FIPS mode).

Digest isValid method

The isValid() method checks whether the digest context is valid and ready to process data. Method declaration:

bool isValid() const;

Returns: TRUE if the context is valid, or FALSE otherwise.

Digest update method

The update(…) method feeds raw data bytes or a string into the incremental digest computation. Method declaration:

bool update(const void* data, size_t size);
bool update(const std::string& text);
Parameter Value
data Pointer to input data buffer.
size Number of bytes to process.
text String whose bytes are absorbed into the digest.

Returns: TRUE on success, or FALSE on failure.

Example:

md.update("First chunk");
md.update("Second chunk");

Digest finish method

The finish(…) method finalizes the digest computation and writes the result into the provided vector. Method declaration:

bool finish(std::vector<uint8_t>& digest);
Parameter Value
digest Output vector receiving the calculated digest bytes.

Returns: TRUE on success, or FALSE on failure.

Digest finalize method

The finalize(…) method finalizes the digest computation and returns the output byte vector. Method declaration:

bool finalize(std::vector<uint8_t>& digest);
std::vector<uint8_t> finalize();
Parameter Value
digest Output vector receiving the digest bytes (when passed by reference).

Returns: TRUE on success when output vector is passed, or output vector directly.

Digest finalizeHex method

The finalizeHex() method finalizes the digest computation and returns the result as a lower-case hexadecimal string. Method declaration:

std::string finalizeHex();

Returns: Lower-case hexadecimal digest string, or empty string on failure.

Example:

std::string hex = md.finalizeHex();

Digest reset method

The reset() method resets the digest state so a new message can be hashed using the same algorithm. Method declaration:

bool reset();

Returns: TRUE on success, or FALSE on failure.

Digest lastError method

The lastError() method returns the description of the last failure encountered by the digest object. Method declaration:

std::string lastError() const;

Returns: Description of the error.

Digest digestSize method

The digestSize(…) method returns the digest output size in bytes for the specified algorithm. Method declaration:

static size_t digestSize(Algo algo);
Parameter Value
algo Target digest algorithm.

Returns: Size in bytes (16 for MD5, 20 for SHA-1, 32 for SHA-256, 48 for SHA-384, 64 for SHA-512), or 0 if algorithm is not a digest.

Digest hash method

The hash(…) method computes the digest over a data buffer in a single one-shot call. Method declaration:

static bool hash(Algo algo, const void* data, size_t size, std::vector<uint8_t>& digest);
Parameter Value
algo Target digest algorithm.
data Pointer to input data.
size Number of bytes to hash.
digest Output vector receiving the digest bytes.

Returns: TRUE on success, or FALSE on failure.

Digest hashHex method

The hashHex(…) method computes the digest of an input string in one shot and returns a lower-case hexadecimal string. Method declaration:

static std::string hashHex(Algo algo, const std::string& text);
Parameter Value
algo Target digest algorithm.
text Input string to hash.

Returns: Lower-case hexadecimal hash string, or empty string on failure.

Digest sha1Hex method

The sha1Hex(…) method computes SHA-1 of an input string and returns a lower-case hexadecimal string. Method declaration:

static std::string sha1Hex(const std::string& in);
Parameter Value
in Input string to hash.

Returns: 40-character lower-case hexadecimal SHA-1 string.

Digest sha256Hex method

The sha256Hex(…) method computes SHA-256 of an input string and returns a lower-case hexadecimal string. Method declaration:

static std::string sha256Hex(const std::string& in);
Parameter Value
in Input string to hash.

Returns: 64-character lower-case hexadecimal SHA-256 string.

Digest sha384Hex method

The sha384Hex(…) method computes SHA-384 of an input string and returns a lower-case hexadecimal string. Method declaration:

static std::string sha384Hex(const std::string& in);
Parameter Value
in Input string to hash.

Returns: 96-character lower-case hexadecimal SHA-384 string.

Digest sha512Hex method

The sha512Hex(…) method computes SHA-512 of an input string and returns a lower-case hexadecimal string. Method declaration:

static std::string sha512Hex(const std::string& in);
Parameter Value
in Input string to hash.

Returns: 128-character lower-case hexadecimal SHA-512 string.

Digest md5Hex method

The md5Hex(…) method computes MD5 of an input string and returns a lower-case hexadecimal string. In FIPS mode, returns an empty string. Method declaration:

static std::string md5Hex(const std::string& in);
Parameter Value
in Input string to hash.

Returns: 32-character lower-case hexadecimal MD5 string, or empty string if disallowed in FIPS mode.

Cipher class description

Cipher class declaration

Cipher class provides symmetric encryption and decryption for AES-CTR, AES-CBC, and AES-GCM modes, modeled after OpenSSL’s EVP_CIPHER_CTX.

namespace cr::crypto
{

class Cipher
{
public:

    Cipher(Algo algo, bool encrypt);

    Cipher(Algo algo, bool encrypt,
           const std::vector<uint8_t>& key,
           const std::vector<uint8_t>& iv,
           bool pkcs7Padding = true);

    ~Cipher();

    bool init(const std::vector<uint8_t>& key,
              const std::vector<uint8_t>& iv);

    bool setAad(const void* aad, size_t aadLen);

    bool update(const void* in, size_t inLen, std::vector<uint8_t>& out);

    bool update(const std::vector<uint8_t>& in, std::vector<uint8_t>& out);

    bool finish(std::vector<uint8_t>& out);

    bool finalize(std::vector<uint8_t>& out);

    bool getTag(std::vector<uint8_t>& tag);

    bool setTag(const void* tag, size_t tagLen);

    bool isValid() const;

    std::string lastError() const;

    static bool encrypt(Algo algo,
                        const std::vector<uint8_t>& key,
                        const std::vector<uint8_t>& iv,
                        const std::vector<uint8_t>& in,
                        std::vector<uint8_t>& out,
                        bool pkcs7Padding = true);

    static bool decrypt(Algo algo,
                        const std::vector<uint8_t>& key,
                        const std::vector<uint8_t>& iv,
                        const std::vector<uint8_t>& in,
                        std::vector<uint8_t>& out,
                        bool pkcs7Padding = true);
};

bool aesCtr(const std::vector<uint8_t>& key, const uint8_t iv[16],
            const uint8_t* in, size_t len, uint8_t* out);

bool aesCbcEncrypt(const std::vector<uint8_t>& key, const uint8_t iv[16],
                   const uint8_t* in, size_t len,
                   std::vector<uint8_t>& out, bool pkcs7Padding = true);

bool aesCbcDecrypt(const std::vector<uint8_t>& key, const uint8_t iv[16],
                   const uint8_t* in, size_t len,
                   std::vector<uint8_t>& out, bool pkcs7Padding = true);

}

Cipher constructor

The Cipher constructor creates a cipher processor for the specified algorithm and direction. Method declaration:

Cipher(Algo algo, bool encrypt);
Cipher(Algo algo, bool encrypt,
       const std::vector<uint8_t>& key,
       const std::vector<uint8_t>& iv,
       bool pkcs7Padding = true);
Parameter Value
algo Cipher algorithm (Algo::Aes128Ctr, Algo::Aes128Cbc, Algo::Aes256Cbc, Algo::Aes128Gcm, Algo::Aes256Gcm).
encrypt TRUE for encryption, FALSE for decryption.
key Secret key buffer (16 bytes for AES-128, 32 bytes for AES-256).
iv Initialization vector / counter block (16 bytes for CTR/CBC, 12 bytes for GCM).
pkcs7Padding TRUE to enable PKCS#7 padding (CBC mode only).

Cipher init method

The init(…) method initializes the cipher with key and IV. Method declaration:

bool init(const std::vector<uint8_t>& key, const std::vector<uint8_t>& iv);
Parameter Value
key Secret key buffer.
iv IV / nonce buffer.

Returns: TRUE on success, or FALSE on failure.

Cipher setAad method

The setAad(…) method supplies Additional Authenticated Data for AEAD modes (AES-GCM). Method declaration:

bool setAad(const void* aad, size_t aadLen);
Parameter Value
aad Pointer to additional authenticated data.
aadLen Length of AAD in bytes.

Returns: TRUE on success, or FALSE on failure.

Cipher update method

The update(…) method processes a chunk of input data through the cipher. Method declaration:

bool update(const void* in, size_t inLen, std::vector<uint8_t>& out);
bool update(const std::vector<uint8_t>& in, std::vector<uint8_t>& out);
Parameter Value
in Pointer to input bytes, or byte vector.
inLen Number of bytes to process.
out Output vector receiving transformed ciphertext or plaintext bytes.

Returns: TRUE on success, or FALSE on failure.

Cipher finish method

The finish(…) method finalizes the cipher operation, appending any remaining padded bytes. Method declaration:

bool finish(std::vector<uint8_t>& out);
Parameter Value
out Output vector receiving any final transformed bytes.

Returns: TRUE on success, or FALSE on failure.

Cipher finalize method

The finalize(…) method is an alias to finish(…). Method declaration:

bool finalize(std::vector<uint8_t>& out);
Parameter Value
out Output vector receiving any final transformed bytes.

Returns: TRUE on success, or FALSE on failure.

Cipher getTag method

The getTag(…) method retrieves the calculated 16-byte authentication tag after AEAD encryption. Method declaration:

bool getTag(std::vector<uint8_t>& tag);
Parameter Value
tag Output vector receiving the 16-byte authentication tag.

Returns: TRUE on success, or FALSE on failure.

Cipher setTag method

The setTag(…) method sets the expected 16-byte authentication tag to verify during AEAD decryption. Method declaration:

bool setTag(const void* tag, size_t tagLen);
Parameter Value
tag Pointer to 16-byte authentication tag.
tagLen Tag length (must be 16).

Returns: TRUE on success, or FALSE on failure.

Cipher isValid method

The isValid() method checks whether the cipher context is valid. Method declaration:

bool isValid() const;

Returns: TRUE if valid, or FALSE otherwise.

Cipher lastError method

The lastError() method returns description of the last failure encountered by the cipher. Method declaration:

std::string lastError() const;

Returns: Description text.

Cipher encrypt method

The encrypt(…) static method performs one-shot symmetric encryption. Method declaration:

static bool encrypt(Algo algo,
                    const std::vector<uint8_t>& key,
                    const std::vector<uint8_t>& iv,
                    const std::vector<uint8_t>& in,
                    std::vector<uint8_t>& out,
                    bool pkcs7Padding = true);
Parameter Value
algo Cipher algorithm (Algo::Aes128Ctr, Algo::Aes128Cbc, Algo::Aes256Cbc).
key Secret key buffer (16 or 32 bytes).
iv Initialization vector (16 bytes).
in Plaintext input vector.
out Output vector receiving ciphertext.
pkcs7Padding TRUE for PKCS#7 padding (CBC mode).

Returns: TRUE on success, or FALSE on failure.

Cipher decrypt method

The decrypt(…) static method performs one-shot symmetric decryption. Method declaration:

static bool decrypt(Algo algo,
                    const std::vector<uint8_t>& key,
                    const std::vector<uint8_t>& iv,
                    const std::vector<uint8_t>& in,
                    std::vector<uint8_t>& out,
                    bool pkcs7Padding = true);
Parameter Value
algo Cipher algorithm.
key Secret key buffer.
iv Initialization vector.
in Ciphertext input vector.
out Output vector receiving decrypted plaintext.
pkcs7Padding TRUE for PKCS#7 padding (CBC mode).

Returns: TRUE on success, or FALSE on failure.

Cipher aesCtr function

The aesCtr(…) free function encrypts or decrypts bytes in-place or into a buffer using AES-128-CTR (RFC 3711 SRTP). Method declaration:

bool aesCtr(const std::vector<uint8_t>& key, const uint8_t iv[16],
            const uint8_t* in, size_t len, uint8_t* out);
Parameter Value
key 16-byte or 32-byte AES key.
iv 16-byte initial counter block.
in Input data bytes.
len Byte length.
out Output buffer of at least len bytes.

Returns: TRUE on success, or FALSE on failure.

Cipher aesCbcEncrypt function

The aesCbcEncrypt(…) free function performs AES-CBC encryption with optional PKCS#7 padding. Method declaration:

bool aesCbcEncrypt(const std::vector<uint8_t>& key, const uint8_t iv[16],
                   const uint8_t* in, size_t len,
                   std::vector<uint8_t>& out, bool pkcs7Padding = true);
Parameter Value
key 16-byte or 32-byte AES key.
iv 16-byte initialization vector.
in Input plaintext pointer.
len Input length.
out Output vector receiving ciphertext.
pkcs7Padding TRUE for PKCS#7 padding.

Returns: TRUE on success, or FALSE on failure.

Cipher aesCbcDecrypt function

The aesCbcDecrypt(…) free function performs AES-CBC decryption with optional PKCS#7 padding. Method declaration:

bool aesCbcDecrypt(const std::vector<uint8_t>& key, const uint8_t iv[16],
                   const uint8_t* in, size_t len,
                   std::vector<uint8_t>& out, bool pkcs7Padding = true);
Parameter Value
key 16-byte or 32-byte AES key.
iv 16-byte initialization vector.
in Input ciphertext pointer.
len Input length.
out Output vector receiving decrypted plaintext.
pkcs7Padding TRUE for PKCS#7 padding.

Returns: TRUE on success, or FALSE on failure.

Aead class description

Aead class declaration

Aead class implements Authenticated Encryption with Associated Data using AES-GCM (NIST SP 800-38D).

namespace cr::crypto
{

class Aead
{
public:

    static bool aeadSeal(Algo algo,
                         const std::vector<uint8_t>& key,
                         const std::vector<uint8_t>& plaintext,
                         const std::vector<uint8_t>& aad,
                         std::vector<uint8_t>& ciphertext,
                         std::vector<uint8_t>& tag,
                         std::vector<uint8_t>& nonce);

    static bool aeadSeal(const std::vector<uint8_t>& key,
                         const std::vector<uint8_t>& plaintext,
                         const std::vector<uint8_t>& aad,
                         std::vector<uint8_t>& sealed);

    static bool aeadOpen(Algo algo,
                         const std::vector<uint8_t>& key,
                         const std::vector<uint8_t>& nonce,
                         const std::vector<uint8_t>& ciphertext,
                         const std::vector<uint8_t>& aad,
                         const std::vector<uint8_t>& tag,
                         std::vector<uint8_t>& plaintext);

    static bool aeadOpen(const std::vector<uint8_t>& key,
                         const std::vector<uint8_t>& sealed,
                         const std::vector<uint8_t>& aad,
                         std::vector<uint8_t>& plaintext);

    static bool aeadSealWithIv(Algo algo,
                               const std::vector<uint8_t>& key,
                               const std::vector<uint8_t>& iv,
                               const std::vector<uint8_t>& plaintext,
                               const std::vector<uint8_t>& aad,
                               std::vector<uint8_t>& ciphertext,
                               std::vector<uint8_t>& tag);

    static bool aeadSealWithIv(const std::vector<uint8_t>& key,
                               const std::vector<uint8_t>& iv,
                               const std::vector<uint8_t>& plaintext,
                               const std::vector<uint8_t>& aad,
                               std::vector<uint8_t>& ciphertext,
                               std::vector<uint8_t>& tag);

    static bool aeadOpenWithIv(Algo algo,
                               const std::vector<uint8_t>& key,
                               const std::vector<uint8_t>& iv,
                               const std::vector<uint8_t>& ciphertext,
                               const std::vector<uint8_t>& aad,
                               const std::vector<uint8_t>& tag,
                               std::vector<uint8_t>& plaintext);

    static bool aeadOpenWithIv(const std::vector<uint8_t>& key,
                               const std::vector<uint8_t>& iv,
                               const std::vector<uint8_t>& ciphertext,
                               const std::vector<uint8_t>& aad,
                               const std::vector<uint8_t>& tag,
                               std::vector<uint8_t>& plaintext);
};

bool aeadSeal(const std::vector<uint8_t>& key,
              const std::vector<uint8_t>& plaintext,
              const std::vector<uint8_t>& aad,
              std::vector<uint8_t>& sealed);

bool aeadOpen(const std::vector<uint8_t>& key,
              const std::vector<uint8_t>& sealed,
              const std::vector<uint8_t>& aad,
              std::vector<uint8_t>& plaintext);

bool aeadSealWithIv(const std::vector<uint8_t>& key,
                    const std::vector<uint8_t>& iv,
                    const std::vector<uint8_t>& plaintext,
                    const std::vector<uint8_t>& aad,
                    std::vector<uint8_t>& ciphertext,
                    std::vector<uint8_t>& tag);

bool aeadOpenWithIv(const std::vector<uint8_t>& key,
                    const std::vector<uint8_t>& iv,
                    const std::vector<uint8_t>& ciphertext,
                    const std::vector<uint8_t>& aad,
                    const std::vector<uint8_t>& tag,
                    std::vector<uint8_t>& plaintext);

}

Aead aeadSeal method

The aeadSeal(…) method encrypts and authenticates plaintext using an internal cryptographically secure random 12-byte nonce. Method declaration:

static bool aeadSeal(Algo algo,
                     const std::vector<uint8_t>& key,
                     const std::vector<uint8_t>& plaintext,
                     const std::vector<uint8_t>& aad,
                     std::vector<uint8_t>& ciphertext,
                     std::vector<uint8_t>& tag,
                     std::vector<uint8_t>& nonce);

static bool aeadSeal(const std::vector<uint8_t>& key,
                     const std::vector<uint8_t>& plaintext,
                     const std::vector<uint8_t>& aad,
                     std::vector<uint8_t>& sealed);
Parameter Value
algo Algorithm (Algo::Aes128Gcm or Algo::Aes256Gcm).
key Secret key (16 or 32 bytes).
plaintext Data bytes to encrypt and authenticate.
aad Additional authenticated data (not encrypted, but authenticated).
ciphertext Output vector receiving ciphertext bytes.
tag Output vector receiving 16-byte authentication tag.
nonce Output vector receiving generated 12-byte nonce.
sealed Combined output format: [12-byte nonce] + [ciphertext] + [16-byte tag].

Returns: TRUE on success, or FALSE on failure.

Aead aeadOpen method

The aeadOpen(…) method verifies the authentication tag and decrypts ciphertext using the provided nonce. Method declaration:

static bool aeadOpen(Algo algo,
                     const std::vector<uint8_t>& key,
                     const std::vector<uint8_t>& nonce,
                     const std::vector<uint8_t>& ciphertext,
                     const std::vector<uint8_t>& aad,
                     const std::vector<uint8_t>& tag,
                     std::vector<uint8_t>& plaintext);

static bool aeadOpen(const std::vector<uint8_t>& key,
                     const std::vector<uint8_t>& sealed,
                     const std::vector<uint8_t>& aad,
                     std::vector<uint8_t>& plaintext);
Parameter Value
algo Algorithm (Algo::Aes128Gcm or Algo::Aes256Gcm).
key Secret key.
nonce 12-byte nonce used during encryption.
ciphertext Ciphertext to decrypt.
aad Additional authenticated data (must match AAD provided at sealing).
tag 16-byte authentication tag to verify.
sealed Combined input vector containing [nonce] + [ciphertext] + [tag].
plaintext Output vector receiving decrypted bytes.

Returns: TRUE if authentic and decrypted successfully, or FALSE if authentication failed or payload was tampered with.

Aead aeadSealWithIv method

The aeadSealWithIv(…) method encrypts and authenticates with a caller-provided 12-byte nonce. Method declaration:

static bool aeadSealWithIv(Algo algo,
                           const std::vector<uint8_t>& key,
                           const std::vector<uint8_t>& iv,
                           const std::vector<uint8_t>& plaintext,
                           const std::vector<uint8_t>& aad,
                           std::vector<uint8_t>& ciphertext,
                           std::vector<uint8_t>& tag);
Parameter Value
algo Cipher algorithm (Algo::Aes128Gcm or Algo::Aes256Gcm).
key Secret key buffer (16 or 32 bytes).
iv Caller-provided 12-byte nonce.
plaintext Data to protect.
aad Additional authenticated data.
ciphertext Output ciphertext buffer.
tag Output 16-byte authentication tag.

Returns: TRUE on success, or FALSE on failure.

Aead aeadOpenWithIv method

The aeadOpenWithIv(…) method decrypts and verifies payload with a caller-provided nonce and tag. Method declaration:

static bool aeadOpenWithIv(Algo algo,
                           const std::vector<uint8_t>& key,
                           const std::vector<uint8_t>& iv,
                           const std::vector<uint8_t>& ciphertext,
                           const std::vector<uint8_t>& aad,
                           const std::vector<uint8_t>& tag,
                           std::vector<uint8_t>& plaintext);
Parameter Value
algo Cipher algorithm (Algo::Aes128Gcm or Algo::Aes256Gcm).
key Secret key buffer.
iv 12-byte nonce buffer.
ciphertext Ciphertext buffer.
aad Additional authenticated data.
tag 16-byte authentication tag.
plaintext Output vector receiving decrypted bytes.

Returns: TRUE if authentic and decrypted, or FALSE if verification failed.

Aead aeadSeal function

The aeadSeal(…) free function encrypts and authenticates plaintext using AES-256-GCM with an automatically generated 12-byte random nonce, producing a sealed payload combining nonce, ciphertext, and tag. Function declaration:

bool aeadSeal(const std::vector<uint8_t>& key,
              const std::vector<uint8_t>& plaintext,
              const std::vector<uint8_t>& aad,
              std::vector<uint8_t>& sealed);
Parameter Value
key 32-byte AES-256 secret key.
plaintext Input data bytes to encrypt.
aad Additional authenticated data.
sealed Output vector receiving [12-byte nonce] + [ciphertext] + [16-byte tag].

Returns: TRUE on success, or FALSE on failure.

Aead aeadOpen function

The aeadOpen(…) free function verifies authentication tag and decrypts a sealed payload created by aeadSeal(…). Function declaration:

bool aeadOpen(const std::vector<uint8_t>& key,
              const std::vector<uint8_t>& sealed,
              const std::vector<uint8_t>& aad,
              std::vector<uint8_t>& plaintext);
Parameter Value
key 32-byte AES-256 secret key.
sealed Sealed payload containing [12-byte nonce] + [ciphertext] + [16-byte tag].
aad Additional authenticated data used when sealing.
plaintext Output vector receiving decrypted bytes.

Returns: TRUE if authentic and decrypted successfully, or FALSE if authentication failed.

Aead aeadSealWithIv function

The aeadSealWithIv(…) free function encrypts and authenticates plaintext using AES-GCM with a caller-provided 12-byte nonce. Function declaration:

bool aeadSealWithIv(const std::vector<uint8_t>& key,
                    const std::vector<uint8_t>& iv,
                    const std::vector<uint8_t>& plaintext,
                    const std::vector<uint8_t>& aad,
                    std::vector<uint8_t>& ciphertext,
                    std::vector<uint8_t>& tag);
Parameter Value
key 16-byte or 32-byte AES key.
iv 12-byte initialization vector / nonce.
plaintext Input data to protect.
aad Additional authenticated data.
ciphertext Output vector receiving ciphertext bytes.
tag Output vector receiving 16-byte authentication tag.

Returns: TRUE on success, or FALSE on failure.

Aead aeadOpenWithIv function

The aeadOpenWithIv(…) free function verifies tag and decrypts ciphertext using a caller-provided 12-byte nonce. Function declaration:

bool aeadOpenWithIv(const std::vector<uint8_t>& key,
                    const std::vector<uint8_t>& iv,
                    const std::vector<uint8_t>& ciphertext,
                    const std::vector<uint8_t>& aad,
                    const std::vector<uint8_t>& tag,
                    std::vector<uint8_t>& plaintext);
Parameter Value
key 16-byte or 32-byte AES key.
iv 12-byte initialization vector / nonce.
ciphertext Input ciphertext bytes.
aad Additional authenticated data.
tag 16-byte authentication tag to verify.
plaintext Output vector receiving decrypted plaintext.

Returns: TRUE if authentic and decrypted, or FALSE if authentication fails.

Hmac class description

Hmac class declaration

Hmac class provides Keyed-Hash Message Authentication Codes (RFC 2104) with SHA-1 and SHA-256.

namespace cr::crypto
{

class Hmac
{
public:

    explicit Hmac(Algo hashAlgo);

    Hmac(Algo hashAlgo, const std::vector<uint8_t>& key);

    ~Hmac();

    bool init(const void* key, size_t keyLen);

    bool update(const void* data, size_t size);

    bool update(const std::string& text);

    bool update(const std::vector<uint8_t>& data);

    bool finish(std::vector<uint8_t>& out);

    bool finalize(std::vector<uint8_t>& out);

    std::vector<uint8_t> finalize();

    bool reset();

    bool isValid() const;

    std::string lastError() const;

    static std::vector<uint8_t> hmac(Algo hashAlgo,
                                     const std::vector<uint8_t>& key,
                                     const std::vector<uint8_t>& data);

    static std::vector<uint8_t> hmacSha1(const std::vector<uint8_t>& key,
                                         const std::vector<uint8_t>& data);

    static std::vector<uint8_t> hmacSha256(const std::vector<uint8_t>& key,
                                           const std::vector<uint8_t>& data);
};

bool hmac(Algo hashAlgo, const void* key, size_t keyLen,
          const void* data, size_t dataLen, std::vector<uint8_t>& out);

bool hmac(Algo hashAlgo, const std::vector<uint8_t>& key,
          const std::vector<uint8_t>& data, std::vector<uint8_t>& out);

bool hmacSha1(const std::vector<uint8_t>& key, const uint8_t* data,
              size_t len, uint8_t* out, size_t outCap, size_t& outLen);

std::vector<uint8_t> hmacSha1(const std::vector<uint8_t>& key,
                              const std::vector<uint8_t>& data);

bool hmacSha256(const std::vector<uint8_t>& key, const uint8_t* data,
                size_t len, uint8_t* out, size_t outCap, size_t& outLen);

std::vector<uint8_t> hmacSha256(const std::vector<uint8_t>& key,
                                const std::vector<uint8_t>& data);

}

Hmac constructor

The Hmac constructor initializes an HMAC processor for the specified hash algorithm. Method declaration:

explicit Hmac(Algo hashAlgo);
Hmac(Algo hashAlgo, const std::vector<uint8_t>& key);
Parameter Value
hashAlgo Underlying hash algorithm (Algo::Sha1, Algo::Sha256).
key Key buffer.

Hmac init method

The init(…) method initializes the HMAC context with a key. Method declaration:

bool init(const void* key, size_t keyLen);
Parameter Value
key Pointer to key data.
keyLen Length of key in bytes.

Returns: TRUE on success, or FALSE on failure.

Hmac update method

The update(…) method feeds raw data bytes, a string, or a byte vector into the HMAC computation. Method declaration:

bool update(const void* data, size_t size);
bool update(const std::string& text);
bool update(const std::vector<uint8_t>& data);
Parameter Value
data Pointer to data buffer, or byte vector.
size Number of bytes to absorb.
text String whose bytes are absorbed.

Returns: TRUE on success, or FALSE on failure.

Hmac finish method

The finish(…) method finalizes the HMAC computation and writes the authentication code into the output vector. Method declaration:

bool finish(std::vector<uint8_t>& out);
Parameter Value
out Output vector receiving the calculated authentication code.

Returns: TRUE on success, or FALSE on failure.

Hmac finalize method

The finalize(…) method finalizes the HMAC computation. Method declaration:

bool finalize(std::vector<uint8_t>& out);
std::vector<uint8_t> finalize();
Parameter Value
out Output vector receiving the calculated authentication code (when passed by reference).

Returns: TRUE on success when output vector is passed, or byte vector containing the MAC directly.

Hmac reset method

The reset() method resets the HMAC context for reuse with the same key. Method declaration:

bool reset();

Returns: TRUE on success, or FALSE on failure.

Hmac isValid method

The isValid() method checks whether the HMAC context is valid. Method declaration:

bool isValid() const;

Returns: TRUE if valid, or FALSE otherwise.

Hmac lastError method

The lastError() method returns description of the last failure encountered by the HMAC object. Method declaration:

std::string lastError() const;

Returns: Description of the error.

Hmac hmac method

The hmac(…) static method computes an HMAC over a byte vector in one shot. Method declaration:

static std::vector<uint8_t> hmac(Algo hashAlgo,
                                 const std::vector<uint8_t>& key,
                                 const std::vector<uint8_t>& data);
Parameter Value
hashAlgo Underlying hash algorithm (Algo::Sha1, Algo::Sha256).
key Secret key vector.
data Input data vector.

Returns: Byte vector containing the calculated authentication code, or empty vector on failure.

Hmac hmacSha1 method

The hmacSha1(…) static method computes an HMAC-SHA1 over a byte vector in one shot. Method declaration:

static std::vector<uint8_t> hmacSha1(const std::vector<uint8_t>& key,
                                     const std::vector<uint8_t>& data);
Parameter Value
key Secret key vector.
data Input data vector.

Returns: 20-byte vector containing the calculated HMAC-SHA1 code.

Hmac hmacSha256 method

The hmacSha256(…) static method computes an HMAC-SHA256 over a byte vector in one shot. Method declaration:

static std::vector<uint8_t> hmacSha256(const std::vector<uint8_t>& key,
                                       const std::vector<uint8_t>& data);
Parameter Value
key Secret key vector.
data Input data vector.

Returns: 32-byte vector containing the calculated HMAC-SHA256 code.

Hmac hmac function

The hmac(…) free function calculates an HMAC over raw data buffers or vectors. Method declaration:

bool hmac(Algo hashAlgo, const void* key, size_t keyLen,
          const void* data, size_t dataLen, std::vector<uint8_t>& out);
bool hmac(Algo hashAlgo, const std::vector<uint8_t>& key,
          const std::vector<uint8_t>& data, std::vector<uint8_t>& out);
Parameter Value
hashAlgo Underlying hash algorithm (Algo::Sha1, Algo::Sha256).
key Pointer to key buffer or key vector.
keyLen Length of key buffer in bytes.
data Pointer to input data or data vector.
dataLen Length of data in bytes.
out Output vector receiving the calculated MAC bytes.

Returns: TRUE on success, or FALSE on failure.

Hmac hmacSha1 function

The hmacSha1(…) free function computes HMAC-SHA1 writing directly into a pre-allocated buffer or returning a byte vector. Method declaration:

bool hmacSha1(const std::vector<uint8_t>& key, const uint8_t* data,
              size_t len, uint8_t* out, size_t outCap, size_t& outLen);
std::vector<uint8_t> hmacSha1(const std::vector<uint8_t>& key,
                              const std::vector<uint8_t>& data);
Parameter Value
key Secret key vector.
data Pointer to input data buffer or data vector.
len Length of input data in bytes.
out Pointer to pre-allocated output buffer (at least 20 bytes).
outCap Capacity of output buffer.
outLen Output reference receiving number of bytes written (20).

Returns: TRUE on success, or FALSE on failure (when vector is return type, returns 20-byte vector).

Hmac hmacSha256 function

The hmacSha256(…) free function computes HMAC-SHA256 writing directly into a pre-allocated buffer or returning a byte vector. Method declaration:

bool hmacSha256(const std::vector<uint8_t>& key, const uint8_t* data,
                size_t len, uint8_t* out, size_t outCap, size_t& outLen);
std::vector<uint8_t> hmacSha256(const std::vector<uint8_t>& key,
                                const std::vector<uint8_t>& data);
Parameter Value
key Secret key vector.
data Pointer to input data buffer or data vector.
len Length of input data in bytes.
out Pointer to pre-allocated output buffer (at least 32 bytes).
outCap Capacity of output buffer.
outLen Output reference receiving number of bytes written (32).

Returns: TRUE on success, or FALSE on failure (when vector is return type, returns 32-byte vector).

Kdf class description

Kdf class declaration

Kdf class provides password-based key derivation (PBKDF2 per RFC 8018) and HMAC-based extract-and-expand key derivation (HKDF per RFC 5869).

namespace cr::crypto
{

class Kdf
{
public:

    static bool deriveKey(const KdfParams& params,
                          const std::vector<uint8_t>& secret,
                          std::vector<uint8_t>& key);

    static std::vector<uint8_t> pbkdf2Sha256(
        const std::string& password,
        const std::vector<uint8_t>& salt,
        uint32_t iterations = CRYPTO_KDF_DEFAULT_ITERATIONS,
        size_t keySize = 32);

    static std::vector<uint8_t> pbkdf2Sha1(
        const std::string& password,
        const std::vector<uint8_t>& salt,
        uint32_t iterations = 1000,
        size_t keySize = 20);

    static std::vector<uint8_t> hkdf(
        Algo hash,
        const std::vector<uint8_t>& ikm,
        const std::vector<uint8_t>& salt,
        const std::vector<uint8_t>& info,
        size_t keySize = 32);
};

bool deriveKey(const KdfParams& params, const std::vector<uint8_t>& secret,
               std::vector<uint8_t>& key);

}

Kdf deriveKey method

The deriveKey(…) method derives a cryptographic key using explicit parameters specified in KdfParams. Method declaration:

static bool deriveKey(const KdfParams& params,
                      const std::vector<uint8_t>& secret,
                      std::vector<uint8_t>& key);
Parameter Value
params Derivation parameters (KdfParams: algorithm, hash, salt, iterations, info, target keySize).
secret Input secret (password or input keying material).
key Output vector receiving derived key bytes.

Returns: TRUE on success, or FALSE on failure (e.g. parameter bounds violated under FIPS policy).

Kdf pbkdf2Sha256 method

The pbkdf2Sha256(…) method derives a key from password using PBKDF2-HMAC-SHA256 (RFC 8018). Method declaration:

static std::vector<uint8_t> pbkdf2Sha256(
    const std::string& password,
    const std::vector<uint8_t>& salt,
    uint32_t iterations = CRYPTO_KDF_DEFAULT_ITERATIONS,
    size_t keySize = 32);
Parameter Value
password Input password string.
salt Salt buffer (recommended >= 16 bytes per NIST SP 800-132).
iterations Iteration count (default 600,000).
keySize Target derived key length in bytes (default 32).

Returns: Derived key vector, or empty vector on failure.

Kdf pbkdf2Sha1 method

The pbkdf2Sha1(…) method derives a key using legacy PBKDF2-HMAC-SHA1 (RFC 2898). Method declaration:

static std::vector<uint8_t> pbkdf2Sha1(
    const std::string& password,
    const std::vector<uint8_t>& salt,
    uint32_t iterations = 1000,
    size_t keySize = 20);
Parameter Value
password Input password string.
salt Salt buffer.
iterations Iteration count (default 1,000).
keySize Target derived key length in bytes (default 20).

Returns: Derived key vector, or empty vector on failure.

Kdf hkdf method

The hkdf(…) method extracts and expands a high-entropy secret using HKDF (RFC 5869). Method declaration:

static std::vector<uint8_t> hkdf(
    Algo hash,
    const std::vector<uint8_t>& ikm,
    const std::vector<uint8_t>& salt,
    const std::vector<uint8_t>& info,
    size_t keySize = 32);
Parameter Value
hash Underlying hash algorithm (Algo::Sha256).
ikm Input keying material (master secret).
salt Optional salt buffer (if empty, defaults to string of zeros).
info Optional application-specific context info.
keySize Target derived key length in bytes (default 32).

Returns: Derived key vector, or empty vector on failure.

Kdf deriveKey function

The deriveKey(…) free function derives a cryptographic key from a secret using PBKDF2 or HKDF parameters. Function declaration:

bool deriveKey(const KdfParams& params, const std::vector<uint8_t>& secret,
               std::vector<uint8_t>& key);
Parameter Value
params Key derivation parameters structure (KdfParams).
secret Input secret material (password or master key).
key Output vector receiving derived key bytes.

Returns: TRUE on success, or FALSE on failure.

Random class description

Random class declaration

Random class provides a cryptographically secure pseudo-random number generator (CSPRNG) based on OS entropy (BCryptGenRandom on Windows, /dev/urandom or OpenSSL on Linux).

namespace cr::crypto
{

class Random
{
public:

    static bool randomBytes(void* buffer, size_t size);

    static bool randomBytes(std::vector<uint8_t>& buffer, size_t size);

    static std::vector<uint8_t> randomBytes(size_t size);

    static bool randomU32(uint32_t& out);

    static uint32_t randomU32();

    static bool randomU16(uint16_t& out);

    static uint16_t randomU16();

    static std::string randomHex(size_t size);

    static std::string uuidV4();
};

bool randomBytes(void* buffer, size_t size);

bool randomBytes(std::vector<uint8_t>& buffer, size_t size);

bool randomU32(uint32_t& out);

bool randomU16(uint16_t& out);

std::string randomHex(size_t size);

std::string uuidV4();

}

Random randomBytes method

The randomBytes(…) method generates cryptographically secure pseudo-random bytes. Method declaration:

static bool randomBytes(void* buffer, size_t size);
static bool randomBytes(std::vector<uint8_t>& buffer, size_t size);
static std::vector<uint8_t> randomBytes(size_t size);
Parameter Value
buffer Output buffer pointer, or output vector resized to size.
size Number of random bytes to generate (up to 65,536 bytes).

Returns: TRUE on success, or FALSE on failure (when vector is passed as return, returns generated byte vector).

Random randomU32 method

The randomU32() method generates a random 32-bit unsigned integer (e.g. for RTP SSRC or random nonces). Method declaration:

static bool randomU32(uint32_t& out);
static uint32_t randomU32();
Parameter Value
out Reference receiving the 32-bit random integer.

Returns: Random 32-bit unsigned integer, or 0 on failure.

Random randomU16 method

The randomU16() method generates a random 16-bit unsigned integer (e.g. for sequence numbers). Method declaration:

static bool randomU16(uint16_t& out);
static uint16_t randomU16();
Parameter Value
out Reference receiving the 16-bit random integer.

Returns: Random 16-bit unsigned integer, or 0 on failure.

Random randomHex method

The randomHex(…) method generates secure random bytes and returns them formatted as a lower-case hexadecimal string. Method declaration:

static std::string randomHex(size_t size);
Parameter Value
size Number of random bytes (resulting string length will be 2 * size).

Returns: Lower-case hexadecimal string, or empty string on failure.

Random uuidV4 method

The uuidV4() method generates an RFC 4122 Version 4 randomly generated UUID. Method declaration:

static std::string uuidV4();

Returns: Formatted UUID string in format "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".

Example:

std::string id = cr::crypto::Random::uuidV4();
// e.g. "e3b0c442-98fc-4c14-9afe-4c4c238b71d0"

Random randomBytes function

The randomBytes(…) free function fills a buffer or vector with cryptographically secure random bytes. Function declaration:

bool randomBytes(void* buffer, size_t size);
bool randomBytes(std::vector<uint8_t>& buffer, size_t size);
Parameter Value
buffer Pointer to destination buffer, or vector resized to size.
size Number of random bytes to generate.

Returns: TRUE on success, or FALSE on failure.

Random randomU32 function

The randomU32(…) free function generates a random 32-bit unsigned integer. Function declaration:

bool randomU32(uint32_t& out);
Parameter Value
out Reference receiving the 32-bit random integer.

Returns: TRUE on success, or FALSE on failure.

Random randomU16 function

The randomU16(…) free function generates a random 16-bit unsigned integer. Function declaration:

bool randomU16(uint16_t& out);
Parameter Value
out Reference receiving the 16-bit random integer.

Returns: TRUE on success, or FALSE on failure.

Random randomHex function

The randomHex(…) free function generates random bytes and returns a lower-case hexadecimal string. Function declaration:

std::string randomHex(size_t size);
Parameter Value
size Number of random bytes (resulting string length will be 2 * size).

Returns: Lower-case hexadecimal string, or empty string on failure.

Random uuidV4 function

The uuidV4() free function generates a random RFC 4122 Version 4 UUID string. Function declaration:

std::string uuidV4();

Returns: Formatted UUID string "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".

Base64 class description

Base64 class declaration

Base64 class provides strict RFC 4648 Base64 encoding/decoding and lower-case Hexadecimal conversion.

namespace cr::crypto
{

class Base64
{
public:

    static std::string encode(const void* data, size_t size);

    static std::string encode(const std::vector<uint8_t>& data);

    static std::string encode(const std::string& text);

    static bool decode(const std::string& text, std::vector<uint8_t>& data);

    static std::string toHex(const void* data, size_t size);

    static std::string toHex(const std::vector<uint8_t>& data);

    static bool fromHex(const std::string& hex, std::vector<uint8_t>& data);
};

std::string base64Encode(const void* data, size_t size);

std::string base64Encode(const std::vector<uint8_t>& data);

bool base64Decode(const std::string& text, std::vector<uint8_t>& data);

std::string hexEncode(const void* data, size_t size);

std::string hexEncode(const std::vector<uint8_t>& data);

}

Base64 encode method

The encode(…) method encodes a raw byte buffer, vector, or string into an RFC 4648 Base64 string with padding. Method declaration:

static std::string encode(const void* data, size_t size);
static std::string encode(const std::vector<uint8_t>& data);
static std::string encode(const std::string& text);
Parameter Value
data Pointer to raw byte buffer, or byte vector.
size Number of bytes to encode.
text Plain text string to encode.

Returns: Base64 encoded string.

Base64 decode method

The decode(…) method strictly decodes an RFC 4648 Base64 string into a byte vector. Rejects malformed input, invalid padding, or illegal characters. Method declaration:

static bool decode(const std::string& text, std::vector<uint8_t>& data);
Parameter Value
text Base64 encoded string.
data Output vector receiving decoded bytes.

Returns: TRUE on successful decode, or FALSE if input string is invalid.

Base64 toHex method

The toHex(…) method converts a raw byte buffer or vector into a lower-case hexadecimal string. Method declaration:

static std::string toHex(const void* data, size_t size);
static std::string toHex(const std::vector<uint8_t>& data);
Parameter Value
data Pointer to raw byte buffer, or byte vector.
size Number of bytes to convert.

Returns: Lower-case hexadecimal string of length 2 * size.

Base64 fromHex method

The fromHex(…) method converts a hexadecimal string into raw bytes. Rejects invalid hex characters or odd-length strings. Method declaration:

static bool fromHex(const std::string& hex, std::vector<uint8_t>& data);
Parameter Value
hex Input hexadecimal string.
data Output vector receiving decoded bytes.

Returns: TRUE on success, or FALSE on invalid hexadecimal input.

Base64 base64Encode function

The base64Encode(…) free function encodes raw bytes or a vector into an RFC 4648 Base64 string. Function declaration:

std::string base64Encode(const void* data, size_t size);
std::string base64Encode(const std::vector<uint8_t>& data);
Parameter Value
data Pointer to raw byte buffer, or byte vector.
size Number of bytes to encode.

Returns: RFC 4648 Base64 encoded string.

Base64 base64Decode function

The base64Decode(…) free function strictly decodes an RFC 4648 Base64 string into a byte vector. Function declaration:

bool base64Decode(const std::string& text, std::vector<uint8_t>& data);
Parameter Value
text Base64 encoded string.
data Output vector receiving decoded bytes.

Returns: TRUE on success, or FALSE if input is malformed.

Base64 hexEncode function

The hexEncode(…) free function encodes raw bytes or a vector into a lower-case hexadecimal string. Function declaration:

std::string hexEncode(const void* data, size_t size);
std::string hexEncode(const std::vector<uint8_t>& data);
Parameter Value
data Pointer to raw byte buffer, or byte vector.
size Number of bytes to convert.

Returns: Lower-case hexadecimal string of length 2 * size.

SecureErase class description

SecureErase class declaration

SecureErase class provides volatile memory wiping utilities to guarantee that sensitive cryptographic keys, passwords, and plaintexts are securely wiped from memory before deallocation.

namespace cr::crypto
{

class SecureErase
{
public:

    static void erase(void* data, size_t size);

    static void erase(std::vector<uint8_t>& buffer);

    static void erase(std::string& text);
};

void secureErase(void* data, size_t size);

void secureErase(std::vector<uint8_t>& buffer);

void secureErase(std::string& text);

}

SecureErase erase method

The erase(…) method zeroes the memory using volatile memory writes or platform-specific secure erasure primitives (SecureZeroMemory on Windows) that are guaranteed not to be optimized away by the compiler. Method declaration:

static void erase(void* data, size_t size);
static void erase(std::vector<uint8_t>& buffer);
static void erase(std::string& text);
Parameter Value
data Pointer to sensitive memory buffer.
size Number of bytes to wipe.
buffer Byte vector whose contents are wiped to zero and cleared.
text String whose contents are wiped to zero and cleared.

Returns: None.

Example:

std::vector<uint8_t> secretKey = ...;
cr::crypto::SecureErase::erase(secretKey);

SecureErase secureErase function

The secureErase(…) free function wipes sensitive memory buffers, vectors, or strings using volatile memory writes that cannot be optimized away by the compiler. Function declaration:

void secureErase(void* data, size_t size);
void secureErase(std::vector<uint8_t>& buffer);
void secureErase(std::string& text);
Parameter Value
data Pointer to memory buffer to wipe.
size Number of bytes to wipe.
buffer Byte vector whose contents are wiped to zero and cleared.
text String whose contents are wiped to zero and cleared.

Returns: None.

Data structures

Mode enum

Declared in CryptoProvider.h:

enum class Mode
{
    Standard,
    Fips
};
Value Description
Mode::Standard Standard operation mode. All supported algorithms permitted.
Mode::Fips FIPS 140-3 compliant mode. Unapproved algorithms (e.g. MD5) disallowed.

Algo enum

Declared in CryptoProvider.h:

enum class Algo
{
    Md5,
    Sha1,
    Sha256,
    Sha384,
    Sha512,
    Aes128Ctr,
    Aes128Cbc,
    Aes256Cbc,
    Aes128Gcm,
    Aes256Gcm,
    HmacSha1,
    HmacSha256,
    Pbkdf2,
    Hkdf
};
Value Standard FIPS 140-3 Approved Description
Algo::Md5 RFC 1321 No (blocked in FIPS) MD5 message digest (128-bit).
Algo::Sha1 FIPS 180-4 Yes SHA-1 message digest (160-bit).
Algo::Sha256 FIPS 180-4 Yes SHA-256 message digest (256-bit).
Algo::Sha384 FIPS 180-4 Yes SHA-384 message digest (384-bit).
Algo::Sha512 FIPS 180-4 Yes SHA-512 message digest (512-bit).
Algo::Aes128Ctr RFC 3711 / SP 800-38A Yes AES-128 stream cipher counter mode.
Algo::Aes128Cbc NIST SP 800-38A Yes AES-128 cipher block chaining mode.
Algo::Aes256Cbc NIST SP 800-38A Yes AES-256 cipher block chaining mode.
Algo::Aes128Gcm NIST SP 800-38D Yes AES-128 Galois/Counter Mode (AEAD).
Algo::Aes256Gcm NIST SP 800-38D Yes AES-256 Galois/Counter Mode (AEAD).
Algo::HmacSha1 RFC 2104 Yes HMAC with SHA-1 hash.
Algo::HmacSha256 RFC 2104 Yes HMAC with SHA-256 hash.
Algo::Pbkdf2 RFC 8018 / SP 800-132 Yes Password-Based Key Derivation Function 2.
Algo::Hkdf RFC 5869 Yes HMAC-based Key Derivation Function.

KdfAlgo enum

Declared in CryptoProvider.h:

enum class KdfAlgo
{
    Pbkdf2,
    Hkdf
};

KdfParams struct

Declared in CryptoProvider.h:

struct KdfParams
{
    KdfAlgo kdf{KdfAlgo::Hkdf};
    Algo hash{Algo::Sha256};
    std::vector<uint8_t> salt;
    uint32_t iterations{600000};
    std::vector<uint8_t> info;
    size_t keySize{32};
    bool legacyPkcs5{false};
};
Field Type Description
kdf KdfAlgo Derivation algorithm choice (KdfAlgo::Pbkdf2 or KdfAlgo::Hkdf).
hash Algo Underlying hash function (e.g. Algo::Sha256).
salt std::vector<uint8_t> Salt buffer.
iterations uint32_t PBKDF2 iteration count (default 600,000).
info std::vector<uint8_t> Context and application-specific info buffer for HKDF.
keySize size_t Target derived key length in bytes (default 32).
legacyPkcs5 bool Allow legacy PKCS#5 vectors (refused in FIPS mode).

Constants

Declared in CryptoProvider.h:

constexpr size_t CRYPTO_DIGEST_SIZE_MD5 = 16;
constexpr size_t CRYPTO_DIGEST_SIZE_SHA1 = 20;
constexpr size_t CRYPTO_DIGEST_SIZE_SHA256 = 32;
constexpr size_t CRYPTO_DIGEST_SIZE_SHA384 = 48;
constexpr size_t CRYPTO_DIGEST_SIZE_SHA512 = 64;

constexpr size_t CRYPTO_AES128_KEY_SIZE = 16;
constexpr size_t CRYPTO_AES256_KEY_SIZE = 32;
constexpr size_t CRYPTO_AES_BLOCK_SIZE = 16;
constexpr size_t CRYPTO_AES_IV_SIZE = 16;
constexpr size_t CRYPTO_GCM_IV_SIZE = 12;
constexpr size_t CRYPTO_GCM_TAG_SIZE = 16;

constexpr size_t CRYPTO_AEAD_KEY_SIZE = 32;
constexpr size_t CRYPTO_AEAD_IV_SIZE = 12;
constexpr size_t CRYPTO_AEAD_TAG_SIZE = 16;

constexpr uint32_t CRYPTO_KDF_MIN_ITERATIONS = 1000;
constexpr size_t CRYPTO_KDF_MIN_SALT_SIZE = 16;
constexpr size_t CRYPTO_KDF_MIN_KEY_SIZE = 14;
constexpr uint32_t CRYPTO_KDF_DEFAULT_ITERATIONS = 600000;
constexpr size_t CRYPTO_KDF_MAX_KEY_SIZE = 1024;

constexpr size_t CRYPTO_RANDOM_MAX_BYTES = 65536;

Build and connect to your project

Backend selection architecture

+-----------------------------------------------------------------+
|                       Client Application                        |
+-----------------------------------------------------------------+
                                |
                                v
+-----------------------------------------------------------------+
|               CryptoProvider Public Interface                   |
|                      (CryptoProvider.h)                         |
+-----------------------------------------------------------------+
                                |
            +-------------------+-------------------+
            |                   |                   |
            v                   v                   v
     [Windows OS]       [Linux + OpenSSL]   [Linux without OpenSSL]
            |                   |                   |
            v                   v                   v
+-------------------+   +---------------+   +---------------------+
| Windows Native    |   | Linux OpenSSL |   | Standalone Custom   |
| CNG (bcrypt.lib)  |   | 3.x           |   | C++ Implementations |
| (Impl/Cng)        |   | (Impl/OpenSsl)|   | (Impl/Custom)       |
+-------------------+   +---------------+   +---------------------+

FIPS 140-3 compliance mode

CryptoProvider is not a validated cryptographic module. In FIPS mode it routes the primitives to a validated module where one is present, and it reports FIPS only with evidence:

  • Linux with OpenSSL: the FIPS mode (requested by the application, or the system flag /proc/sys/crypto/fips_enabled) loads the system OpenSSL configuration and the fips and base providers into a private OSSL_LIB_CTX and enables the FIPS default properties. FIPS is reported only when that context proves enforcement (SHA2-256 resolves, MD5 does not) and the DRBG answers. A FIPS 140-3 claim needs a validated OpenSSL FIPS provider installed as its Security Policy requires; the provider of a distribution is usually not the validated one.
  • Windows: FIPS is reported while the Windows FIPS policy is on (BCryptGetFipsAlgorithmMode), and MD5 is refused then. The CNG primitives are validated by Microsoft; AES-CTR, PBKDF2 and HKDF are composed by CryptoProvider from CNG primitives, outside that module.
  • Linux without OpenSSL: the standalone implementations are never reported as FIPS.

Physical source exclusion for certification

To comply with strict cybersecurity and software certification standards:

  • On Windows: Custom standalone implementations and Linux OpenSSL files are excluded from compilation via CMake file filtering.
  • On Linux with OpenSSL: Standalone custom algorithms are physically excluded from compilation.
  • On Linux without OpenSSL: Standalone custom algorithms are compiled from Impl/Custom.

CMake integration

Option 1: Standalone build

# Clone the repository
git clone https://github.com/ConstantRobotics-Ltd/CryptoProvider.git
cd CryptoProvider

# Configure and build
cmake -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build --config Release

# Run tests
./build/bin/Release/CryptoProviderTest

Option 2: Add as Git submodule / sub-repository

In your project’s CMakeLists.txt:

add_subdirectory(CryptoProvider)
target_link_libraries(${PROJECT_NAME} PRIVATE CryptoProvider)

Simple example

The following standalone example demonstrates initialization, hashing, random generation, AEAD encryption, and password-based key derivation:

#include <iostream>
#include <string>
#include <vector>

#include "CryptoProvider.h"

using namespace cr::crypto;

int main()
{
    // 1. Initialize CryptoProvider
    if (!CryptoProvider::init(Mode::Standard))
    {
        std::cerr << "Initialization failed!" << std::endl;
        return -1;
    }

    std::cout << "CryptoProvider v" << CryptoProvider::getVersion()
              << " initialized successfully." << std::endl;

    // 2. Hash message with SHA-256
    std::string sha256 = Digest::sha256Hex("The quick brown fox jumps over the lazy dog");
    std::cout << "SHA-256: " << sha256 << std::endl;

    // 3. Generate secure random key and UUID
    std::vector<uint8_t> key = Random::randomBytes(32);
    std::string sessionUuid   = Random::uuidV4();
    std::cout << "Session UUID: " << sessionUuid << std::endl;

    // 4. Authenticated Encryption (AEAD AES-256-GCM)
    std::string secretMessage = "Confidential telemetry packet";
    std::string authHeader    = "Device-ID-704";
    std::vector<uint8_t> plaintext(secretMessage.begin(), secretMessage.end());
    std::vector<uint8_t> aad(authHeader.begin(), authHeader.end());
    std::vector<uint8_t> ciphertext, tag, nonce;

    if (Aead::aeadSeal(Algo::Aes256Gcm, key, plaintext, aad,
                       ciphertext, tag, nonce))
    {
        std::cout << "AEAD Ciphertext (hex): " << Base64::toHex(ciphertext) << std::endl;
        std::cout << "AEAD Tag (hex):        " << Base64::toHex(tag) << std::endl;

        // Decrypt and verify
        std::vector<uint8_t> decrypted;
        if (Aead::aeadOpen(Algo::Aes256Gcm, key, nonce, ciphertext, aad, tag, decrypted))
        {
            std::string recovered(decrypted.begin(), decrypted.end());
            std::cout << "Decrypted message:    \"" << recovered << "\"" << std::endl;
        }
    }

    // 5. Derive key from password using PBKDF2-HMAC-SHA256
    std::vector<uint8_t> salt = Random::randomBytes(16);
    std::vector<uint8_t> derived = Kdf::pbkdf2Sha256("UserPassword", salt, 600000, 32);
    std::cout << "Derived Key (hex): " << Base64::toHex(derived) << std::endl;

    // 6. Securely wipe sensitive keys
    SecureErase::erase(key);
    SecureErase::erase(derived);

    return 0;
}

Table of contents