cryptoprovider_web_logo

CryptoProvider C++ library

v1.4.0

Table of contents

Overview

CryptoProvider is a 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) by default. Serves the FIPS mode only while the Windows FIPS policy is on (BCryptGetFipsAlgorithmMode), and refuses MD5 and a standard request then. CNG has no SHA-224, so this backend refuses Algo::Sha224 and Algo::HmacSha224 (isSupported method). The OpenSSL backend below can be selected instead (see Backend selection option).
  2. Linux with OpenSSL: Uses installed OpenSSL 3.x (the default backend on Linux and other non-Windows systems when OpenSSL 3.0 or newer is found; it can be selected on Windows too, see Backend selection option) via a private OSSL_LIB_CTX (FIPS and standard providers). If the application requests the FIPS mode, it loads the FIPS provider, refuses a context in which any provider other than fips and base is active, and reports FIPS only when the context proves enforcement (SHA2-256 resolves, MD5 does not). If FIPS mode is enabled on the system (/proc/sys/crypto/fips_enabled), a standard request is refused.
  3. Linux without OpenSSL 3.x (and other non-Windows systems without it): Automatically compiles and uses built-in, standalone C++ implementations of all required cryptographic algorithms (MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, AES-128/192/256-CTR, AES-128/192/256-CBC, AES-128/192/256-CFB, AES-128/256-GCM, HMAC, PBKDF2, HKDF, /dev/urandom CSPRNG). The standalone implementations have no digital signatures: the Ecdsa methods fail there. They have no FIPS mode: a FIPS request is refused, and so is a standard request on a system with FIPS mode enabled.
  4. Exclusion of the standalone sources: 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 the following cryptographic operations:

  • Digests: Incremental streaming and one-shot MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512. MD5 and SHA-1 can be left out of the build (MD5 and SHA-1 option).
  • Symmetric Ciphers: AES-128-CTR (for SRTP encryption per RFC 3711), AES-128-CBC, AES-256-CBC with PKCS#7 padding, and AES-128/192/256-CFB with 128-bit feedback (the mode of the SNMPv3 privacy protocols, RFC 3826). The free functions take AES-192 keys in CTR and CBC as well.
  • Authenticated Encryption (AEAD): AES-128-GCM and AES-256-GCM with 16-byte authentication tags (12 to 16 bytes in the raw-pointer overloads) and 12-byte nonces, made for every seal (with OpenSSL generated inside the provider) or, in the standard mode, given by the caller.
  • Message Authentication: HMAC with SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512 (streaming and one-shot).
  • Digital signatures: ECDSA on the NIST P-256 curve with SHA-256 (FIPS 186-5): key pair generation, signing and verification with raw keys and DER encoded signatures, in the OpenSSL and CNG backends.
  • Key Derivation (KDF): PBKDF2-HMAC-SHA256 / SHA1 with NIST SP 800-132 bounds enforcement (not for the legacy PKCS#5 mode in the standard mode, see KdfParams struct), 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 over the whole capacity of a buffer (SecureErase).

The library uses C++17 standard. On Windows it has zero external dependencies with the default CNG backend (system bcrypt only); the OpenSSL backend requires OpenSSL 3.0 or newer on any system. On other systems OpenSSL 3.0 or newer is optional: without it the standalone implementations are built (no ECDSA, no FIPS mode).

CryptoProvider is general-purpose software: it is not tied to any sector or application, and the developer of a program decides what the program does with it.

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.
1.1.0 14.10.2026 - FIPS module configuration (FipsConfig), refusal reasons (FipsError), fipsModuleVersion() and runFipsSelfTest(); the base provider is mandatory in the FIPS mode.
- Backend option <PARENT>_CRYPTOPROVIDER_BACKEND; the OpenSSL backend and its FIPS provider work on Windows.
- Breaking: the OpenSSL backend needs OpenSSL 3.0 or newer; an older OpenSSL selects the standalone backend.
1.2.0 15.10.2026 - ECDSA P-256 with SHA-256 (Ecdsa, Algo::EcdsaP256Sha256) in the OpenSSL and CNG backends.
- CryptoProvider::backendName(), supportsFipsConfig() and FipsConfig::ignoreEnvironment.
- Breaking: FipsError::None is renamed FipsError::NoError.
1.2.1 25.10.2026 - The standalone AES and MD5 are rewritten with identical results: CBC decryption about 75 % faster, other modes and digests a few percent.
- Documentation: the standalone AES uses table look-ups, so its time depends on the key and the data.
1.3.0 27.10.2026 - AES-CFB (Algo::Aes128Cfb, Aes192Cfb, Aes256Cfb, Cipher), SHA-224, HMAC-SHA-224, -384 and -512, isSupported() and FipsConfig::requireTlsEmsCheck; option <PARENT>_CRYPTOPROVIDER_MD5_SHA1 OFF removes MD5 and SHA-1.
- Fixed: AES-192 keys; unverified GCM plaintext left in the buffer; isFipsAvailable() poisoning later FIPS requests; unwiped key material.
- Breaking: a key length that does not match the algorithm is refused, with 24 bytes for AES-128 and for GCM; after a failed self-test every primitive and init() refuse.
1.3.1 29.10.2026 - Fixed: OpenSSL and CNG objects leaked, and a key copy was freed unwiped, when memory ran out while a digest or HMAC context was created.
1.4.0 29.10.2026 - One crypto mode per process: the first init() sets it.
- With OpenSSL aeadSeal() makes its nonce internally.
- Refusals, invalid input too, set lastError() and wipe secrets.
- Breaking, now refused: the other crypto mode; Mode::Standard where the system requires FIPS; Mode::Fips on standalone; FIPS providers beyond fips and base; ignoreEnvironment against an environment-located module; in the FIPS mode, caller-IV GCM encryption and HMAC keys or HKDF input keying material under 14 bytes; a GCM IV not 12 bytes or tag under 12; an HMAC truncated under 4 bytes; Hmac/Cipher reuse after finish(); use before init().

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, AES-CFB, AES-GCM).
        Digest.cpp ------------ Message digest implementation.
        Ecdsa.cpp ------------- ECDSA P-256 argument checks and dispatch to the backend.
        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.
            CngEcdsaDer.h ----- ECDSA signature DER and raw (r, s) conversion header.
            CngEcdsaDer.cpp --- ECDSA signature strict DER and raw (r, s) conversion.
        OpenSsl --------------- OpenSSL 3.x backend (default on non-Windows systems, selectable on Windows).
            OpenSslBackend.h -- OpenSSL backend header.
            OpenSslBackend.cpp  OpenSSL backend implementation.
        Custom ---------------- Standalone custom cryptographic implementations.
            CustomAes.h ------- Standalone AES-128/192/256 cipher header.
            CustomAes.cpp ----- Standalone AES-128/192/256 cipher implementation.
            CustomGcm.h ------- Standalone GCM mode header.
            CustomGcm.cpp ----- Standalone GCM mode implementation.
            CustomDigestBlocks.h - Message blocks and padding of the standalone digests.
            CustomWipe.h ------ Memory wipe of the standalone implementations that the compiler keeps.
            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/224 digest header.
            CustomSha256.cpp -- Standalone SHA-256/224 digest implementation.
            CustomSha512.h ---- Standalone SHA-512/384 digest header.
            CustomSha512.cpp -- Standalone SHA-512/384 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 ------------------ Automated unit and known-answer tests.
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 rapidpixel
{

class CryptoProvider
{
public:

    static std::string getVersion();

    static std::string backendName();

    static bool supportsFipsConfig();

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

    static bool init(Mode mode, const FipsConfig& fips,
                     FipsError* error = nullptr);

    static std::string fipsModuleVersion();

    static bool runFipsSelfTest(FipsError* error = nullptr);

    static bool isReady();

    static Mode requestedMode();

    static bool isFipsActive();

    static bool isFipsAvailable();

    static void* nativeContext();

    static bool isAllowed(Algo algo);

    static bool isAllowed(Algo algo, Mode mode);

    static bool isSupported(Algo algo);

    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: " << rapidpixel::CryptoProvider::getVersion() << std::endl;

backendName method

The backendName() method returns the name of the backend the library was built with. The name is known at build time: it does not depend on init(). Method declaration:

static std::string backendName();

Returns: "openssl-<version>" with the version of the linked OpenSSL (for example "openssl-3.0.13"), "windows-cng" or "standalone".

supportsFipsConfig method

The supportsFipsConfig() method checks whether the backend loads a FIPS module that FipsConfig struct can locate. Method declaration:

static bool supportsFipsConfig();

Returns: TRUE for the OpenSSL backend. FALSE for the CNG and standalone backends: CNG refuses a FipsConfig that sets a path, a version or the approved settings with FipsError::NotSupported, and the standalone backend refuses every Mode::Fips request with FipsError::NotSupported.

init method

The init(…) method establishes the crypto mode of the process (Mode::Standard or Mode::Fips) and initializes the backend for it. Method declaration:

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

static bool init(Mode mode, const FipsConfig& fips, FipsError* error = nullptr);
Parameter Value
mode Target operational mode (Mode::Standard or Mode::Fips). Default is Mode::Standard.
fips Where the FIPS module comes from and what it has to be, see FipsConfig struct. Applies to the FIPS mode only. The first overload uses a default-constructed FipsConfig.
error Receives the reason of a refusal, FipsError::NoError on success, see FipsError enum. May be nullptr.

Returns: TRUE if the mode is established, or FALSE on a refusal, with the reason in error and in lastError().

One mode per process. The first successful call establishes the mode for the life of the process. The same mode again is served by the context in force. The other mode is refused with FipsError::ModeConflict, and lastError() is "the crypto mode is already established as Standard" (or "... as Fips"). There is no upgrade of a standard process to the FIPS mode: the objects made in the standard mode would go on computing outside the module. A refused call establishes nothing, so a later call is free to choose the mode.

Only fips and base in the FIPS context. With the OpenSSL backend, a configuration that activates any other provider next to the module (default, legacy, null or a third-party one) is refused with FipsError::NotEnforced, and lastError() names it, for example provider "default" is active in the FIPS context. Such a provider would offer its unapproved implementations through nativeContext() and to queries with other properties.

An operating system that requires FIPS. When the system requires FIPS 140-3 (/proc/sys/crypto/fips_enabled = 1 on Linux with the OpenSSL and standalone backends, the Windows FIPS policy with CNG), a Mode::Standard request, through either overload, is refused with FipsError::ModeConflict and lastError() is "the operating system requires the FIPS mode; initialise with Mode::Fips". The refusal comes before any module is loaded and whatever mode is in force; it establishes nothing, so a following init(Mode::Fips, ...) is free to bring the module up. A Mode::Fips request is served or refused as on any other system, with the reason of the module. The mode in force is therefore always the mode asked for. On Windows the OpenSSL backend does not read the Windows FIPS policy, see CMake integration.

After a failed FIPS self-test every call, in either mode, is refused with FipsError::SelfTestFailed, see runFipsSelfTest method.

One FIPS module per process. The FIPS module is loaded once per process and never replaced, so a later FIPS request is served by the module in force when that module satisfies it and refused otherwise:

  • an empty path accepts the module in force, a non-empty one has to name the same file (an equivalent spelling such as <dir>/. matches), or the request is refused with FipsError::ModulePathConflict;
  • requiredVersion and requireApprovedSettings are checked on the module in force itself, not on the request that loaded it;
  • a request with ignoreEnvironment is refused with FipsError::ModulePathConflict when the environment located the module in force, that is when the request that loaded it did not ignore the environment and left moduleDir empty while OPENSSL_MODULES was set, or configFile empty while OPENSSL_CONF was set (set but empty counts, as it does for OpenSSL). lastError() is then "The OpenSSL FIPS provider in force was located through OPENSSL_MODULES and OPENSSL_CONF, which the request ignores" (or the one variable). On its own such a request would load another module, or none. A module located by the caller’s paths serves it.

A refused request leaves the module in force as it is. The OpenSSL backend is the only one with a loadable module. The CNG backend serves Mode::Fips only under the Windows FIPS policy, and refuses a FipsConfig that sets a path, a version or the approved settings with FipsError::NotSupported (ignoreEnvironment has no effect there). The standalone backend has no FIPS module: it refuses Mode::Fips with FipsError::NotSupported ("FIPS mode is not supported by the standalone backend"), and with FipsError::ModeConflict once the standard mode is established. On a system that requires FIPS it refuses Mode::Standard as above, so it cannot serve such a system at all.

Example:

bool ok = rapidpixel::CryptoProvider::init(rapidpixel::Mode::Standard);
if (!ok)
{
    std::cerr << "Initialization failed: " << rapidpixel::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: before init(), and for good after a failed FIPS self-test (see runFipsSelfTest()).

While it is FALSE every service of every backend is refused: random bytes, digests, HMAC, AES, AEAD, KDF, ECDSA and the objects, with lastError() "Crypto backend not initialised" before init() once the arguments of the call pass (the error state of a failed self-test has a reason of its own).

Example:

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

requestedMode method

The requestedMode() method returns the mode asked for by the init() call that established the crypto mode. That is always the mode in force: isFipsActive method returns TRUE exactly when it is Mode::Fips. Method declaration:

static Mode requestedMode();

Returns: The requested Mode enum value (Mode::Standard or Mode::Fips), Mode::Standard before init().

Example:

rapidpixel::Mode mode = rapidpixel::CryptoProvider::requestedMode();

isFipsActive method

The isFipsActive() method reports whether FIPS 140-3 compliance policy is actively enforced, because the init() call that established the crypto mode asked for Mode::Fips. A system that requires FIPS does not switch it on by itself: a standard request is refused there (see init method). Method declaration:

static bool isFipsActive();

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

Example:

if (rapidpixel::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.

On the OpenSSL backend, available means that OpenSSL’s default configuration activates the FIPS module. The check never loads the module without that configuration, so it does not affect a later init() in FIPS mode with a FipsConfig of its own.

Example:

bool canFips = rapidpixel::CryptoProvider::isFipsAvailable();

fipsModuleVersion method

The fipsModuleVersion() method returns the version the FIPS module in force reports. The value comes from the module itself, which loads only after it has verified its own integrity against the MAC in fipsmodule.cnf. Method declaration:

static std::string fipsModuleVersion();

Returns: Version string, e.g. "3.1.2"; empty when no FIPS module is in force and always with the CNG and standalone backends.

Example:

std::cout << "FIPS module: " << rapidpixel::CryptoProvider::fipsModuleVersion() << std::endl;

runFipsSelfTest method

The runFipsSelfTest(…) method runs the self-tests of the FIPS module in force on demand (ISO/IEC 19790 7.10.3). A failure is permanent for the life of the process: the module enters the error state of ISO/IEC 19790 7.10, which offers no services. isReady() is FALSE from then on, every primitive refuses, and every later init() (in either mode) and self-test is refused with FipsError::SelfTestFailed. Method declaration:

static bool runFipsSelfTest(FipsError* error = nullptr);
Parameter Value
error Receives the reason of a failure, FipsError::NoError on success. FipsError::NotActive when no FIPS module is in force, FipsError::NotSupported with the CNG and standalone backends. May be nullptr.

Returns: TRUE if a FIPS module is in force and every self-test passed, or FALSE otherwise, with the reason in lastError().

Example:

rapidpixel::FipsError error;
if (!rapidpixel::CryptoProvider::runFipsSelfTest(&error))
{
    std::cerr << "Self-test failed: " << rapidpixel::CryptoProvider::lastError() << std::endl;
}

nativeContext method

The nativeContext() method returns the native library context of the OpenSSL backend: the context every primitive of the provider runs in (the FIPS module in FIPS mode), for code that builds its own OpenSSL objects on the same provider, for example a TLS context with SSL_CTX_new_ex(). The context is never freed while the process runs. Method declaration:

static void* nativeContext();

Returns: OSSL_LIB_CTX* of the OpenSSL backend, nullptr for the other backends or before init().

Example:

auto* libCtx = static_cast<OSSL_LIB_CTX*>(rapidpixel::CryptoProvider::nativeContext());
SSL_CTX* sslCtx = SSL_CTX_new_ex(libCtx, nullptr, TLS_client_method());

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 (rapidpixel::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. In the FIPS mode only Algo::Md5 is refused by the method. The overload without mode returns FALSE before a successful init().

The answer is about the algorithm only. In the FIPS mode an allowed algorithm is still refused for a use the module does not approve: AES-GCM encryption with a caller IV, and an HMAC key or HKDF input keying material shorter than CRYPTO_FIPS_MIN_KEY_SIZE (see the usage rules in FIPS 140-3 compliance mode).

Example:

bool md5Allowed = rapidpixel::CryptoProvider::isAllowed(rapidpixel::Algo::Md5);

isSupported method

The isSupported(…) method checks whether the backend the library was built with implements an algorithm at all, whatever the mode. It is known at build time and does not depend on init(). Method declaration:

static bool isSupported(Algo algo);
Parameter Value
algo Algorithm to check (rapidpixel::Algo).

Returns: TRUE if the backend implements the algorithm, or FALSE otherwise. FALSE for Algo::Sha224 and Algo::HmacSha224 on the CNG backend (Windows CNG has no SHA-224) and for Algo::EcdsaP256Sha256 on the standalone backend; TRUE for everything else.

Example:

if (!rapidpixel::CryptoProvider::isSupported(rapidpixel::Algo::HmacSha224))
{
    // Refuse a configuration that needs HMAC-SHA-224 before it is used.
}

lastError method

The lastError() method returns the descriptive text of the last failure on the calling thread. The text is kept per thread: every refusal of the library sets it on the thread that made the call, and no other thread’s failure changes it; init() sets it on the calling thread only. Method declaration:

static std::string lastError();

Returns: String describing the last failure of the calling thread, or empty string if there was none.

The OpenSSL backend never takes a reason from the caller’s OpenSSL error queue, and it leaves that queue as it found it: the errors OpenSSL raises inside a call, served or refused, are dropped when the call returns, and the entries the caller had queued before the call stay.

Example:

std::string err = rapidpixel::CryptoProvider::lastError();

setLastError method

The setLastError(…) method stores a descriptive error text for the calling thread; the other threads keep theirs. Method declaration:

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

Returns: None.

Example:

rapidpixel::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: the time depends on the size only. The comparison is the backend’s: CRYPTO_memcmp() with OpenSSL, a loop that accumulates the differences through a volatile byte with the standalone and CNG backends; the standalone AES-GCM tag check uses the same comparison. 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. A null pointer with a non-zero size compares unequal.
b Pointer to second memory buffer, or second string. A null pointer with a non-zero size compares unequal.
size Number of bytes to compare; zero bytes compare equal. Strings of different sizes are unequal.

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

Example:

bool match = rapidpixel::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. Every refusal, of an object or of the one-shot hash(), sets CryptoProvider::lastError() of the calling thread; an object keeps the same text in its own lastError().

namespace rapidpixel
{

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 sha224Hex(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:

rapidpixel::Digest md(rapidpixel::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; nullptr only with a size of zero, a null pointer with a length is refused.
size Number of bytes to process (with CNG at most ULONG_MAX per call).
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; every refusal sets the same text in CryptoProvider::lastError() of the calling thread. 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; nullptr only with a size of zero.
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 sha224Hex method

The sha224Hex(…) method computes SHA-224 (FIPS 180-4) of an input string and returns a lower-case hexadecimal string. Method declaration:

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

Returns: 56-character lower-case hexadecimal SHA-224 string, or an empty string where the backend has no SHA-224 (CNG).

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, AES-CFB and AES-GCM modes, modeled after OpenSSL’s EVP_CIPHER_CTX. Every refusal, of an object, of the one-shot encrypt() and decrypt() or of the free AES functions below, sets CryptoProvider::lastError() of the calling thread; an object keeps the same text in its own lastError().

A cipher object collects its input with update() and processes it in finish(). One init() serves one finish(): before init() and after finish(), whatever its result, the object refuses setAad(), update(), setTag() and finish() with a reason ("Cipher is not keyed: init() it first", "Cipher is spent by finish(): init() it again") until init() keys it again, so a key and IV pair is never used twice by accident. This holds for every mode, CTR, CBC, CFB and GCM. finish() erases the input it collected, and a refused finish() erases its output over the capacity like any other failure; the additional authenticated data is erased over its capacity at the next init() and on destruction. A refused init() leaves the object unkeyed: the previous key is never left in use. An AES-CTR, AES-CBC or AES-CFB object takes an IV of exactly 16 bytes; init() refuses any other size. The data and the additional authenticated data of one init() are at most INT_MAX bytes each, and a null pointer with a non-zero length is refused. setTag() serves an AES-GCM decryption before its finish(), getTag() an AES-GCM encryption after its finish(); the other uses are refused.

The one-shot encrypt(…) and decrypt(…) and the free aesCbcEncrypt() and aesCbcDecrypt() compute their result into a buffer of the library and hand it over at the end, so their output vector may be the input, the key or the IV; a failure leaves it erased over its capacity and empty. The free AES functions refuse a null key or IV, a null input or output with a non-zero length, and a length above INT_MAX, before any memory is read; an AES-CBC encryption with padding refuses a length above INT_MAX - 16, whose ciphertext would not fit INT_MAX bytes.

namespace rapidpixel
{

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 aesCtr(const void* key, size_t keyLen, 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 aesCbcEncrypt(const void* key, size_t keyLen, 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);

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

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

bool aesCfbEncrypt(const void* key, size_t keyLen, const uint8_t iv[16],
                   const uint8_t* in, size_t len, uint8_t* out);

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

bool aesCfbDecrypt(const void* key, size_t keyLen, const uint8_t iv[16],
                   const uint8_t* in, size_t len, uint8_t* out);

}

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, Algo::Aes128Cfb, Algo::Aes192Cfb, Algo::Aes256Cfb).
encrypt TRUE for encryption, FALSE for decryption.
key Secret key buffer (16 bytes for AES-128, 24 bytes for AES-192, 32 bytes for AES-256). An empty key leaves the cipher unkeyed until init(…); any other key is given to init(…) and refused as by it, which leaves the cipher unkeyed.
iv Initialization vector / counter block (16 bytes for CTR/CBC/CFB, 12 bytes for GCM; a CTR, CBC or CFB IV of another size is refused by init(…), which leaves the cipher unkeyed, a GCM IV of another size by finish(…)).
pkcs7Padding Not used: a Cipher object always uses PKCS#7 padding in CBC mode. The one-shot encrypt(…) / decrypt(…) methods and the free functions use the parameter.

Cipher init method

The init(…) method keys the cipher with key and IV, discarding the input the previous key collected; a cipher spent by finish(…) is usable again. A refused init() leaves the cipher unkeyed: the previous key and its data are never used. In the FIPS mode an AES-GCM cipher object for encryption is refused, with Cipher::lastError() "AES-GCM encryption with a caller IV is not approved in the FIPS mode: the IV must be generated inside the module": its IV would come from the caller (see FIPS 140-3 compliance mode). The constructor that takes a key leaves such an object unkeyed the same way. Seal with aeadSeal(…) instead. An AES-GCM cipher object for decryption is served in both modes. Method declaration:

bool init(const std::vector<uint8_t>& key, const std::vector<uint8_t>& iv);
Parameter Value
key Secret key buffer. An algorithm that names its key length (Algo::Aes128Cbc, Algo::Aes256Cbc, the CFB and GCM ones) takes only that length; Algo::Aes128Ctr takes 16, 24 or 32 bytes, the size selecting AES-128, AES-192 or AES-256, and finish(…) refuses another. An empty key is refused.
iv IV / nonce buffer; an empty IV is refused. AES-CTR, AES-CBC and AES-CFB (Algo::Aes128Ctr, Algo::Aes128Cbc, Algo::Aes256Cbc and the CFB ones) take exactly CRYPTO_AES_IV_SIZE (16) bytes, the block every one of them reads: any other size is refused with "AES IV of N bytes refused, expected 16", and the cipher is left unkeyed.

Returns: TRUE on success, or FALSE on failure.

Cipher setAad method

The setAad(…) method supplies Additional Authenticated Data for AEAD modes (AES-GCM), after init() and before finish(). The cipher erases the AAD it collects over its capacity wherever it drops it, at the next init() and on destruction, as it erases the collected input. Method declaration:

bool setAad(const void* aad, size_t aadLen);
Parameter Value
aad Pointer to additional authenticated data. May be nullptr only if aadLen is zero.
aadLen Length of AAD in bytes. The AAD of one init() is at most INT_MAX bytes.

Returns: TRUE on success, or FALSE on failure.

Cipher update method

The update(…) method passes a chunk of input data to the cipher, after init() and before finish(). The data is collected in the object and processed by finish(…): out is returned empty. 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. May be nullptr only if inLen is zero.
inLen Number of bytes to process. The input of one init() is at most INT_MAX bytes.
out Output vector, cleared by the method once the input is taken, so it may be the input vector (the result is returned by finish(…)).

Returns: TRUE on success, or FALSE on failure.

Cipher finish method

The finish(…) method finalizes the cipher operation: it processes all data passed to update(…) since init() and returns the whole result. It is refused before init() and after a previous finish(); whatever its result, the cipher needs init() again afterwards, and the input it collected is erased. An AES-GCM decryption needs setTag(…) first and fails when the tag does not verify. The result is written into out directly, so the library keeps no copy of a plaintext, and a failure, a refusal included, erases out over its capacity and leaves it empty: a decryption refused for its padding or its tag has no plaintext left behind. Method declaration:

bool finish(std::vector<uint8_t>& out);
Parameter Value
out Output vector receiving the transformed bytes of all data passed to update(…); on a failure erased over its capacity and left empty.

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; on a failure erased over its capacity and left empty.

Returns: TRUE on success, or FALSE on failure.

Cipher getTag method

The getTag(…) method retrieves the calculated 16-byte authentication tag of an AES-GCM encryption, after its finish(). It is refused before finish() and for a decryption. Method declaration:

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

Returns: TRUE on success, or FALSE on failure.

Cipher setTag method

The setTag(…) method sets the authentication tag an AES-GCM decryption verifies, after init() and before finish(). It is refused for an encryption and for CTR, CBC and CFB. A refused tag clears an earlier one, so finish() then fails rather than verify the earlier tag. Method declaration:

bool setTag(const void* tag, size_t tagLen);
Parameter Value
tag Pointer to the authentication tag: the leading tagLen bytes of the full tag. A null pointer is refused.
tagLen Tag length, 12 (CRYPTO_GCM_MIN_TAG_SIZE) to 16 (CRYPTO_GCM_TAG_SIZE) bytes (NIST SP 800-38D); any other length is refused.

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; every refusal sets the same text in CryptoProvider::lastError() of the calling thread. Method declaration:

std::string lastError() const;

Returns: Description text.

Cipher encrypt method

The encrypt(…) static method performs one-shot symmetric encryption. The result is computed into a buffer of the library and handed over at the end, so out may be in, key or iv: the call may write into its own input. A failure, a refusal included, leaves out erased over its capacity and empty, and with it an input that out is. 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, Algo::Aes128Cfb, Algo::Aes192Cfb, Algo::Aes256Cfb).
key Secret key buffer. For CTR and CBC its size (16, 24 or 32 bytes) selects AES-128, AES-192 or AES-256, also for Algo::Aes128Ctr and Algo::Aes128Cbc; for AES-CFB it must be the size the algorithm names, or the call fails.
iv Initialization vector (16 bytes).
in Plaintext input vector, at most INT_MAX bytes; with AES-CBC and padding at most INT_MAX - 16, so that the ciphertext fits INT_MAX bytes too.
out Output vector receiving ciphertext; may be in, key or iv; erased over its capacity and left empty on a failure.
pkcs7Padding TRUE for PKCS#7 padding (CBC mode).

Returns: TRUE on success, or FALSE on failure, with the reason in CryptoProvider::lastError().

Cipher decrypt method

The decrypt(…) static method performs one-shot symmetric decryption. The rules of encrypt(…) apply: out may be in, key or iv, and a failure leaves it erased and empty. 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, at most INT_MAX bytes.
out Output vector receiving decrypted plaintext; may be in, key or iv; on a failure, a wrong padding included, erased over its capacity and left empty.
pkcs7Padding TRUE for PKCS#7 padding (CBC mode).

Returns: TRUE on success, or FALSE on failure, with the reason in CryptoProvider::lastError().

Cipher aesCtr function

The aesCtr(…) free function encrypts or decrypts bytes in-place or into a buffer using AES-CTR: AES-128-CTR (RFC 3711 SRTP) with a 16-byte key, AES-192-CTR with a 24-byte key, AES-256-CTR with a 32-byte key. 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);
bool aesCtr(const void* key, size_t keyLen, const uint8_t iv[16],
            const uint8_t* in, size_t len, uint8_t* out);
Parameter Value
key 16-, 24- or 32-byte AES key: AES-128, AES-192 or AES-256; any other length and a null key are refused.
keyLen Key length in bytes.
iv 16-byte initial counter block; must not be nullptr.
in Input data bytes. May be nullptr only if len is zero.
len Byte length, at most INT_MAX; a longer one is refused before any memory is read.
out Output buffer of at least len bytes; may be the same as in. May be nullptr only if len is zero.

Returns: TRUE on success, or FALSE on failure, with the reason in CryptoProvider::lastError().

Cipher aesCbcEncrypt function

The aesCbcEncrypt(…) free function performs AES-CBC encryption with optional PKCS#7 padding. The result is computed into a buffer of the library and handed over at the end, so out may be the vector that holds in, the key or the IV: the call may write into its own input. 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);
bool aesCbcEncrypt(const void* key, size_t keyLen, const uint8_t iv[16],
                   const uint8_t* in, size_t len,
                   std::vector<uint8_t>& out, bool pkcs7Padding = true);
Parameter Value
key 16-, 24- or 32-byte AES key: AES-128, AES-192 or AES-256; any other length and a null key are refused.
keyLen Key length in bytes.
iv 16-byte initialization vector; must not be nullptr.
in Input plaintext pointer. May be nullptr only if len is zero.
len Input length, at most INT_MAX, and with pkcs7Padding at most INT_MAX - 16 (CRYPTO_AES_BLOCK_SIZE), so that the padded ciphertext fits INT_MAX bytes too; a longer one is refused with a reason before anything is allocated or read.
out Output vector receiving ciphertext; may hold in, the key or the IV; erased over its capacity and left empty on a failure, and with it an input it holds.
pkcs7Padding TRUE for PKCS#7 padding.

Returns: TRUE on success, or FALSE on failure, with the reason in CryptoProvider::lastError().

Cipher aesCbcDecrypt function

The aesCbcDecrypt(…) free function performs AES-CBC decryption with optional PKCS#7 padding. As with aesCbcEncrypt(…), out may be the vector that holds in, the key or the IV. 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);
bool aesCbcDecrypt(const void* key, size_t keyLen, const uint8_t iv[16],
                   const uint8_t* in, size_t len,
                   std::vector<uint8_t>& out, bool pkcs7Padding = true);
Parameter Value
key 16-, 24- or 32-byte AES key; any other length and a null key are refused.
keyLen Key length in bytes.
iv 16-byte initialization vector; must not be nullptr.
in Input ciphertext pointer. May be nullptr only if len is zero.
len Input length, at most INT_MAX; a longer one is refused before anything is allocated or read.
out Output vector receiving decrypted plaintext; may hold in, the key or the IV; on a failure, a wrong padding included, erased over its capacity and left empty, and with it an input it holds.
pkcs7Padding TRUE for PKCS#7 padding.

Returns: TRUE on success, or FALSE on failure, with the reason in CryptoProvider::lastError().

Cipher aesCfbEncrypt function

The aesCfbEncrypt(…) free function performs AES-CFB encryption with 128-bit feedback (NIST SP 800-38A 6.3), the mode of the SNMPv3 privacy protocols (RFC 3826 and its AES-192 and AES-256 extensions). It is a stream mode: there is no padding, the output is as long as the input, and the last block may be partial. Method declaration:

bool aesCfbEncrypt(const std::vector<uint8_t>& key, const uint8_t iv[16],
                   const uint8_t* in, size_t len, uint8_t* out);
bool aesCfbEncrypt(const void* key, size_t keyLen, const uint8_t iv[16],
                   const uint8_t* in, size_t len, uint8_t* out);
Parameter Value
key AES key: 16, 24 or 32 bytes for AES-128, AES-192 or AES-256. Any other length and a null key are refused.
keyLen Key length in bytes.
iv 16-byte initialization vector; must not be nullptr.
in Input plaintext pointer. May be nullptr only if len is zero.
len Input length, at most INT_MAX; a longer one is refused before any memory is read. 0 is accepted and writes nothing.
out Output buffer of at least len bytes; may be the same as in. May be nullptr only if len is zero.

Returns: TRUE on success, or FALSE on failure (the content of out is then undefined), with the reason in CryptoProvider::lastError().

Cipher aesCfbDecrypt function

The aesCfbDecrypt(…) free function performs AES-CFB decryption with 128-bit feedback. Method declaration:

bool aesCfbDecrypt(const std::vector<uint8_t>& key, const uint8_t iv[16],
                   const uint8_t* in, size_t len, uint8_t* out);
bool aesCfbDecrypt(const void* key, size_t keyLen, const uint8_t iv[16],
                   const uint8_t* in, size_t len, uint8_t* out);
Parameter Value
key AES key: 16, 24 or 32 bytes for AES-128, AES-192 or AES-256. Any other length and a null key are refused.
keyLen Key length in bytes.
iv 16-byte initialization vector; must not be nullptr.
in Input ciphertext pointer. May be nullptr only if len is zero.
len Input length, at most INT_MAX; a longer one is refused before any memory is read. 0 is accepted and writes nothing.
out Output buffer of at least len bytes; may be the same as in. May be nullptr only if len is zero.

Returns: TRUE on success, or FALSE on failure (the content of out is then undefined), with the reason in CryptoProvider::lastError().

Example:

// The key is derived from keying material the application holds (here
// sharedSecret, with HKDF); the IV is fresh for every message.
rapidpixel::KdfParams params;
params.kdf = rapidpixel::KdfAlgo::Hkdf;
params.keySize = rapidpixel::CRYPTO_AES128_KEY_SIZE;
std::vector<uint8_t> key;
const std::vector<uint8_t> iv = rapidpixel::Random::randomBytes(rapidpixel::CRYPTO_AES_IV_SIZE);
const std::string text = "scoped PDU";
std::vector<uint8_t> cipher(text.size());
std::vector<uint8_t> plain(text.size());
if (iv.size() != rapidpixel::CRYPTO_AES_IV_SIZE ||
    !rapidpixel::Kdf::deriveKey(params, sharedSecret, key) ||
    !rapidpixel::aesCfbEncrypt(key, iv.data(), reinterpret_cast<const uint8_t*>(text.data()),
                               text.size(), cipher.data()) ||
    !rapidpixel::aesCfbDecrypt(key, iv.data(), cipher.data(), cipher.size(), plain.data()))
{
    // No random octets, refused key length or backend failure.
}
rapidpixel::secureErase(key);

Aead class description

Aead class declaration

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

init() must have succeeded, otherwise every method fails, with "Crypto backend not initialised" in lastError() once the sizes below pass. The sizes are checked first, before anything is read or written:

  • the key size selects the cipher in every method and function: a 16-byte key (CRYPTO_AES128_KEY_SIZE) runs AES-128-GCM and a 32-byte key (CRYPTO_AES256_KEY_SIZE) AES-256-GCM; any other key size is refused. The algo argument does not choose either: a call that takes one refuses any algorithm but Algo::Aes128Gcm and Algo::Aes256Gcm with "AEAD algorithm refused, expected Algo::Aes128Gcm or Algo::Aes256Gcm", and runs the AES-GCM of the key size under either name;
  • the IV is 12 bytes (CRYPTO_GCM_IV_SIZE);
  • a tag is 16 bytes (CRYPTO_GCM_TAG_SIZE), except in the raw-pointer overloads, which take 12 to 16 bytes (CRYPTO_GCM_MIN_TAG_SIZE to CRYPTO_GCM_TAG_SIZE, NIST SP 800-38D): the leading bytes of the full tag;
  • the plaintext or ciphertext and the additional authenticated data are at most INT_MAX bytes each.

aeadSeal() makes the 12-byte nonce of every seal and returns it, or puts it in front of the sealed message. With the OpenSSL backend no IV is handed to the cipher: the cipher generates it inside the provider with the provider’s DRBG (NIST SP 800-38D 8.2.2; in the FIPS mode the DRBG of the module), and the library reads it back. The standalone and CNG backends have no validated module to generate it: they draw it (/dev/urandom, BCryptGenRandom) and hand it to the cipher. The sealed format is unchanged, so data sealed by an earlier version opens, and data sealed now opens with an earlier version.

Encryption with a caller IV, aeadSealWithIv() in every overload, is served in the standard mode and refused in the FIPS mode with lastError() "AES-GCM encryption with a caller IV is not approved in the FIPS mode: the IV must be generated inside the module", the vector outputs left empty and the raw buffers not written: the Security Policy of the OpenSSL FIPS provider makes an IV imported for an encryption a non-conformance (see FIPS 140-3 compliance mode). Decryption with a given IV, aeadOpen() and aeadOpenWithIv(), is served in both modes.

Every refusal sets CryptoProvider::lastError(). Plaintext reaches the caller only once the tag verifies: a vector output receives none and is left empty, a raw output buffer has its first ctLen bytes zeroed when the tag does not verify and is left as it was when the call is refused before decryption. A seal refused for its algorithm or sizes makes no nonce, and a refused seal leaves its output vectors empty. The vector forms run into vectors of the library and hand them over on success, so an output vector may be one of the input vectors (aeadSeal(key, buf, aad, buf), aeadOpen(key, buf, aad, buf)); a refusal leaves that output empty, and so erases the input it shares storage with. The raw-pointer seal runs into buffers of the library and writes the caller’s ciphertext and tag buffers only on success, so a refusal or a backend failure leaves them as they were and an output may overlap an input.

namespace rapidpixel
{

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(Algo algo,
                               const void* key, size_t keyLen,
                               const void* iv, size_t ivLen,
                               const void* plaintext, size_t ptLen,
                               const void* aad, size_t aadLen,
                               void* ciphertext,
                               void* tag, size_t tagLen = 16);

    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(Algo algo,
                               const void* key, size_t keyLen,
                               const void* iv, size_t ivLen,
                               const void* ciphertext, size_t ctLen,
                               const void* aad, size_t aadLen,
                               const void* tag, size_t tagLen,
                               void* 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);

bool aeadSealWithIv(Algo algo,
                    const void* key, size_t keyLen,
                    const void* iv, size_t ivLen,
                    const void* plaintext, size_t ptLen,
                    const void* aad, size_t aadLen,
                    void* ciphertext,
                    void* tag, size_t tagLen = 16);

bool aeadOpenWithIv(Algo algo,
                    const void* key, size_t keyLen,
                    const void* iv, size_t ivLen,
                    const void* ciphertext, size_t ctLen,
                    const void* aad, size_t aadLen,
                    const void* tag, size_t tagLen,
                    void* plaintext);

}

Aead aeadSeal method

The aeadSeal(…) method encrypts and authenticates plaintext under a random 12-byte nonce made for the call, once the algorithm and the sizes are accepted: with OpenSSL the cipher generates it inside the provider and the library reads it back, the standalone and CNG backends draw it (see Aead class declaration). Served in both modes. 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); any other algorithm is refused. Either one runs the AES-GCM the key size selects: AES-128-GCM (16 bytes) or AES-256-GCM (32 bytes).
key Secret key (16 or 32 bytes); any other size is refused.
plaintext Data bytes to encrypt and authenticate.
aad Additional authenticated data (not encrypted, but authenticated).
ciphertext Output vector receiving ciphertext bytes; empty on a refusal.
tag Output vector receiving 16-byte authentication tag; empty on a refusal.
nonce Output vector receiving the 12-byte nonce the message was sealed under; empty on a refusal.
sealed Combined output format: [12-byte nonce] + [ciphertext] + [16-byte tag]; empty on a refusal.

Returns: TRUE on success, or FALSE on failure, with the reason in CryptoProvider::lastError().

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); any other algorithm is refused. Either one runs the AES-GCM the key size selects: AES-128-GCM (16 bytes) or AES-256-GCM (32 bytes).
key Secret key (16 or 32 bytes); any other size is refused.
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]; shorter than nonce and tag is refused.
plaintext Output vector receiving decrypted bytes. Empty when the tag does not verify or the call is refused: unverified plaintext is never returned.

Returns: TRUE if authentic and decrypted successfully, or FALSE if authentication failed or payload was tampered with, with the reason in CryptoProvider::lastError().

Aead aeadSealWithIv method

The aeadSealWithIv(…) method encrypts and authenticates with a caller-provided 12-byte nonce, in the standard mode. In the FIPS mode every overload is refused with "AES-GCM encryption with a caller IV is not approved in the FIPS mode: the IV must be generated inside the module", the vector outputs left empty and the raw buffers not written. The raw-pointer overload serves SRTP (RFC 7714) and takes a tag of 12 to 16 bytes; SRTP with AES-GCM therefore works in the standard mode only (in the FIPS mode an SRTP stack negotiates AES_CM_128_HMAC_SHA1_80). 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);

static bool aeadSealWithIv(Algo algo,
                           const void* key, size_t keyLen,
                           const void* iv, size_t ivLen,
                           const void* plaintext, size_t ptLen,
                           const void* aad, size_t aadLen,
                           void* ciphertext,
                           void* tag, size_t tagLen = 16);
Parameter Value
algo Algorithm (Algo::Aes128Gcm or Algo::Aes256Gcm); any other algorithm is refused. Either one runs the AES-GCM the key size selects: AES-128-GCM (16 bytes) or AES-256-GCM (32 bytes).
key Secret key buffer (16 or 32 bytes); any other size is refused.
keyLen Key length in bytes.
iv Caller-provided 12-byte nonce.
ivLen Nonce length in bytes.
plaintext Data to protect.
ptLen Data length in bytes.
aad Additional authenticated data.
aadLen Additional authenticated data length in bytes.
ciphertext Output ciphertext: a vector, empty on a refusal, or a buffer of ptLen bytes, written only on success (it may overlap an input).
tag Output tag: a 16-byte vector, empty on a refusal, or a buffer of tagLen bytes, written only on success.
tagLen Tag length, 12 (CRYPTO_GCM_MIN_TAG_SIZE) to 16 (CRYPTO_GCM_TAG_SIZE) bytes: the leading bytes of the full tag.

Returns: TRUE on success, or FALSE on failure, with the reason in CryptoProvider::lastError().

Aead aeadOpenWithIv method

The aeadOpenWithIv(…) method decrypts and verifies payload with a caller-provided nonce and tag, in both modes. The raw-pointer overload serves SRTP (RFC 7714) and takes a tag of 12 to 16 bytes. 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);

static bool aeadOpenWithIv(Algo algo,
                           const void* key, size_t keyLen,
                           const void* iv, size_t ivLen,
                           const void* ciphertext, size_t ctLen,
                           const void* aad, size_t aadLen,
                           const void* tag, size_t tagLen,
                           void* plaintext);
Parameter Value
algo Algorithm (Algo::Aes128Gcm or Algo::Aes256Gcm); any other algorithm is refused. Either one runs the AES-GCM the key size selects: AES-128-GCM (16 bytes) or AES-256-GCM (32 bytes).
key Secret key buffer (16 or 32 bytes); any other size is refused.
keyLen Key length in bytes.
iv 12-byte nonce buffer.
ivLen Nonce length in bytes.
ciphertext Ciphertext buffer.
ctLen Ciphertext length in bytes.
aad Additional authenticated data.
aadLen Additional authenticated data length in bytes.
tag Authentication tag: 16 bytes in the vector form.
tagLen Tag length, 12 (CRYPTO_GCM_MIN_TAG_SIZE) to 16 (CRYPTO_GCM_TAG_SIZE) bytes: the leading bytes of the full tag.
plaintext Output plaintext. A vector receives the decrypted bytes only once the tag verifies and is empty otherwise. A buffer of ctLen bytes, which may be the ciphertext buffer itself, has those bytes zeroed when the tag does not verify, and is left as it was when the call is refused before decryption.

Returns: TRUE if authentic and decrypted, or FALSE if verification failed, with the reason in CryptoProvider::lastError().

Aead aeadSeal function

The aeadSeal(…) free function encrypts and authenticates plaintext using AES-GCM (AES-128-GCM or AES-256-GCM, selected by the key size) under a random 12-byte nonce made for the call (with OpenSSL generated inside the provider), producing a sealed payload combining nonce, ciphertext, and tag. Served in both modes. 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 16-byte (AES-128) or 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]; empty on a refusal. It may be one of the inputs.

Returns: TRUE on success, or FALSE on failure, with the reason in CryptoProvider::lastError().

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 16-byte (AES-128) or 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. Empty when the tag does not verify or the call is refused: unverified plaintext is never returned. It may be one of the inputs.

Returns: TRUE if authentic and decrypted successfully, or FALSE if authentication failed, with the reason in CryptoProvider::lastError().

Aead aeadSealWithIv function

The aeadSealWithIv(…) free function encrypts and authenticates plaintext using AES-GCM with a caller-provided 12-byte nonce, in the standard mode; refused in the FIPS mode as aeadSealWithIv method. 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; empty on a refusal.
tag Output vector receiving 16-byte authentication tag; empty on a refusal.

Returns: TRUE on success, or FALSE on failure, with the reason in CryptoProvider::lastError().

Aead aeadOpenWithIv function

The aeadOpenWithIv(…) free function verifies tag and decrypts ciphertext using a caller-provided 12-byte nonce, in both modes. 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. Empty when the tag does not verify or the call is refused: unverified plaintext is never returned.

Returns: TRUE if authentic and decrypted, or FALSE if authentication fails, with the reason in CryptoProvider::lastError().

Hmac class description

Hmac class declaration

Hmac class provides Keyed-Hash Message Authentication Codes (RFC 2104) with SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512. Every refusal, of an object or of the one-shot hmac(), hmacSha1() and hmacSha256(), sets CryptoProvider::lastError() of the calling thread; an object keeps the same text in its own lastError().

An Hmac is keyed by its constructor or by init(). While it is unkeyed, because it was never keyed or because its last init() was refused, update(), finish() and reset() are refused. One key serves one finish(): after finish(), whatever its result, update() and finish() are refused until reset() keys the Hmac again with the same key or init() with a new one; a copy carries the state, so a copy of an unkeyed or spent Hmac is unkeyed or spent too. A null data or key pointer with a non-zero length is refused, by an object and by the one-shot calls. An empty key (nullptr with length 0, or an empty vector) given to init() or to a one-shot call is a key: it gives the RFC 2104 value, zeros padded to the block size, with every backend; a constructor given an empty key leaves the Hmac unkeyed instead. A refused finish() or one-shot hmac() leaves its output vector empty, erased over its capacity.

In the FIPS mode a key shorter than CRYPTO_FIPS_MIN_KEY_SIZE (14 bytes, 112 bits, NIST SP 800-131A), the empty key included, is refused by every HMAC call of every HMAC algorithm: the constructors and init() (the Hmac is left unkeyed), the one-shot hmac(), hmacSha1(), hmacSha256() and the static Hmac::hmac*(), with lastError() "HMAC key of N bytes refused in the FIPS mode, at least 14 (112 bits, SP 800-131A)" (see the usage rules in FIPS 140-3 compliance mode). In the standard mode every key size is served. PBKDF2, whose HMAC key is the password, and the HKDF salt, the HMAC key of its extract step, are not under this rule (see Kdf class declaration).

namespace rapidpixel
{

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);
Hmac(Algo hashAlgo, const void* key, size_t keyLen);
Hmac(Algo hashAlgo, const std::string& key);
Parameter Value
hashAlgo Underlying hash algorithm (Algo::Sha1, Algo::Sha256).
key Key buffer, vector or string. An empty key leaves the Hmac unkeyed until init(…). Any other key goes to init(…) and is refused as by it, in the FIPS mode a key shorter than CRYPTO_FIPS_MIN_KEY_SIZE too: the Hmac stays unkeyed and lastError() says why.
keyLen Key length in bytes; a null key with a non-zero keyLen goes to init(), which refuses it.

Hmac init method

The init(…) method keys the HMAC context, dropping the previous key and the data it absorbed. A refused init() leaves the Hmac unkeyed: update(), finish() and reset() are refused until a good init(). Method declaration:

bool init(const void* key, size_t keyLen);
Parameter Value
key Pointer to key data; nullptr only with a keyLen of zero, the empty key.
keyLen Length of key in bytes; in the FIPS mode at least CRYPTO_FIPS_MIN_KEY_SIZE (14), a shorter key is refused.

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. It is refused while the Hmac is unkeyed, and after finish(…) until reset() or init(…). 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; a null pointer with a non-zero size is refused.
size Number of bytes to absorb (with CNG at most ULONG_MAX per call).
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. It is refused while the Hmac is unkeyed, and after a previous finish(), whatever its result, until reset() or init(…): a second finish() would return no HMAC. Method declaration:

bool finish(std::vector<uint8_t>& out);
Parameter Value
out Output vector receiving the calculated authentication code; on a failure erased over its capacity and left empty.

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); on a failure erased over its capacity and left empty.

Returns: TRUE on success when output vector is passed, or byte vector containing the MAC directly (empty on a failure, so a second finalize() without reset() returns nothing).

Hmac reset method

The reset() method resets the HMAC context for reuse with the same key, also after finish(). It is refused while the Hmac is unkeyed. 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; every refusal sets the same text in CryptoProvider::lastError() of the calling thread. 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; in the FIPS mode at least CRYPTO_FIPS_MIN_KEY_SIZE (14) bytes, a shorter key is refused.
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; in the FIPS mode at least CRYPTO_FIPS_MIN_KEY_SIZE (14) bytes, a shorter key is refused.
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; in the FIPS mode at least CRYPTO_FIPS_MIN_KEY_SIZE (14) bytes, a shorter key is refused.
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; a null key with a non-zero keyLen is refused, and in the FIPS mode a keyLen under CRYPTO_FIPS_MIN_KEY_SIZE (14).
data Pointer to input data or data vector; a null pointer with a non-zero dataLen is refused.
dataLen Length of data in bytes.
out Output vector receiving the calculated MAC bytes; on a failure erased over its capacity and left empty.

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. The buffer forms truncate the MAC to the capacity of the buffer: they write its leading bytes, as SRTP’s 80- and 32-bit tags (RFC 3711). A capacity under CRYPTO_HMAC_MIN_TRUNCATED_SIZE (4 bytes, 32 bits, NIST SP 800-107) and a null buffer are refused. The full MAC the library computes first is erased. 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);
bool hmacSha1(const void* key, size_t keyLen, 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, or pointer to the key (nullptr only with a keyLen of zero); in the FIPS mode at least CRYPTO_FIPS_MIN_KEY_SIZE (14) bytes, a shorter key is refused.
keyLen Key length in bytes.
data Pointer to input data buffer or data vector.
len Length of input data in bytes.
out Pointer to pre-allocated output buffer; must not be nullptr.
outCap Capacity of output buffer: at least CRYPTO_HMAC_MIN_TRUNCATED_SIZE, a smaller one is refused.
outLen Output reference receiving number of bytes written: the smaller of outCap and 20, 0 on failure.

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

Hmac hmacSha256 function

The hmacSha256(…) free function computes HMAC-SHA256 writing directly into a pre-allocated buffer or returning a byte vector. The buffer form truncates the MAC to the capacity of the buffer: it writes its leading bytes. A capacity under CRYPTO_HMAC_MIN_TRUNCATED_SIZE (4 bytes, 32 bits, NIST SP 800-107) and a null buffer are refused. 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; in the FIPS mode at least CRYPTO_FIPS_MIN_KEY_SIZE (14) bytes, a shorter key is refused.
data Pointer to input data buffer or data vector.
len Length of input data in bytes.
out Pointer to pre-allocated output buffer; must not be nullptr.
outCap Capacity of output buffer: at least CRYPTO_HMAC_MIN_TRUNCATED_SIZE, a smaller one is refused.
outLen Output reference receiving number of bytes written: the smaller of outCap and 32, 0 on failure.

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

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).

A key size the derivation cannot produce is refused with a reason before anything is allocated, and no size makes a block count wrap: HKDF above 255 hash blocks (RFC 5869: 8160 bytes with SHA-256, 16320 with SHA-512), PBKDF2 above INT_MAX bytes (the length OpenSSL takes as an int, the bound of every backend). HKDF serves the full 255 blocks with every backend. CRYPTO_KDF_MAX_KEY_SIZE is not enforced. A key size of 0 is never useful and is refused by both derivations with every backend, with lastError() "KDF key size 0 refused: a derived key has at least one byte".

The key is derived into a buffer of the library and handed over on success, so the output vector may be the secret (deriveKey(params, secret, secret) replaces the secret with the key derived from it) or a vector of the parameters. A refusal erases the output vector and leaves it empty, and so erases the secret it shares storage with.

In the FIPS mode HKDF input keying material shorter than CRYPTO_FIPS_MIN_KEY_SIZE (14 bytes, 112 bits, NIST SP 800-131A), the empty one included, is refused by hkdf() and by deriveKey() with KdfAlgo::Hkdf, with lastError() "HKDF input keying material of N bytes refused in the FIPS mode, at least 14 (112 bits, SP 800-131A)"; in the standard mode it is served. The salt is not under that rule, although HKDF’s extract step uses it as the HMAC key: an empty salt is legal (RFC 5869, NIST SP 800-56C), the strength comes from the input keying material. Nor is the PBKDF2 password, the HMAC key of PBKDF2: NIST SP 800-132 governs it, with the salt, iteration and key-size bounds the FIPS mode enforces.

namespace rapidpixel
{

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); HKDF input keying material is at least CRYPTO_FIPS_MIN_KEY_SIZE (14) bytes in the FIPS mode.
key Output vector receiving derived key bytes; it may be the secret. On a failure erased over its capacity and left empty.

Returns: TRUE on success, or FALSE on failure (e.g. parameter bounds violated under FIPS policy, or a key size the derivation cannot produce: 0, HKDF above 255 hash blocks, PBKDF2 above INT_MAX bytes).

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), 1 to INT_MAX.

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

An iteration count below 1,000 or a salt shorter than 16 bytes switches the derivation to the legacy PKCS#5 mode (KdfParams::legacyPkcs5): in the standard mode the key is then derived without the NIST SP 800-132 checks, in the FIPS mode the method fails.

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), 1 to INT_MAX.

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

The method always uses the legacy PKCS#5 mode (KdfParams::legacyPkcs5): in the standard mode the NIST SP 800-132 checks are not applied, in the FIPS mode the method fails.

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); in the FIPS mode at least CRYPTO_FIPS_MIN_KEY_SIZE (14) bytes, shorter material is refused.
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): from 1 to the RFC 5869 maximum of 255 hash blocks (8160 bytes with SHA-256), served by every backend; 0 and a longer key are refused.

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); HKDF input keying material is at least CRYPTO_FIPS_MIN_KEY_SIZE (14) bytes in the FIPS mode.
key Output vector receiving derived key bytes; it may be the secret. On a failure erased over its capacity and left empty.

Returns: TRUE on success, or FALSE on failure.

Ecdsa class description

Ecdsa class declaration

Ecdsa class provides ECDSA digital signatures on the NIST P-256 curve with SHA-256 (FIPS 186-5). Keys are raw: a private key is the 32-byte big-endian scalar d with 1 <= d < n, a public key is the 65-byte uncompressed SEC1 point 0x04 || X || Y that has to lie on the curve. A signature is the DER encoding of SEQUENCE { INTEGER r, INTEGER s } (X9.62, RFC 3279), 8 to 72 bytes. Only the canonical DER encoding is accepted by verify: a BER long-form length, a redundant leading zero byte, a negative or zero integer, a trailing byte and every other encoding are rejected, with every backend. The message is hashed with SHA-256 inside. Signing is randomized: two signatures of the same message differ.

The algorithm is provided by the OpenSSL backend (also in its FIPS module) and by the CNG backend, and it is permitted in the standard and in the FIPS mode (Algo::EcdsaP256Sha256). The standalone backend has no implementation: every method fails and lastError() says so. init() has to succeed first, otherwise every method fails. All methods are thread-safe. The reason of a failure is available from CryptoProvider::lastError().

namespace rapidpixel
{

class Ecdsa
{
public:

    static bool generateKeyPair(std::vector<uint8_t>& privateKey,
                                std::vector<uint8_t>& publicKey);

    static bool sign(const std::vector<uint8_t>& privateKey,
                     const void* message, size_t size,
                     std::vector<uint8_t>& signature);

    static bool sign(const std::vector<uint8_t>& privateKey,
                     const std::vector<uint8_t>& message,
                     std::vector<uint8_t>& signature);

    static bool verify(const std::vector<uint8_t>& publicKey,
                       const void* message, size_t size,
                       const void* signature, size_t signatureSize);

    static bool verify(const std::vector<uint8_t>& publicKey,
                       const std::vector<uint8_t>& message,
                       const std::vector<uint8_t>& signature);
};

}

Ecdsa generateKeyPair method

The generateKeyPair(…) method generates a key pair. Method declaration:

static bool generateKeyPair(std::vector<uint8_t>& privateKey,
                            std::vector<uint8_t>& publicKey);
Parameter Value
privateKey Receives the private key, 32 bytes (CRYPTO_ECDSA_P256_PRIVATE_KEY_SIZE). Secret: wipe it with SecureErase::erase when it is not needed.
publicKey Receives the public key, 65 bytes (CRYPTO_ECDSA_P256_PUBLIC_KEY_SIZE).

Returns: TRUE on success, or FALSE on failure. On failure both vectors are empty and the private key buffer has been wiped.

Example:

std::vector<uint8_t> privateKey;
std::vector<uint8_t> publicKey;
if (!rapidpixel::Ecdsa::generateKeyPair(privateKey, publicKey))
{
    std::cerr << "Key generation failed: " << rapidpixel::CryptoProvider::lastError() << std::endl;
}

Ecdsa sign method

The sign(…) method signs a message. Method declaration:

static bool sign(const std::vector<uint8_t>& privateKey,
                 const void* message, size_t size,
                 std::vector<uint8_t>& signature);

static bool sign(const std::vector<uint8_t>& privateKey,
                 const std::vector<uint8_t>& message,
                 std::vector<uint8_t>& signature);
Parameter Value
privateKey Private key: exactly 32 bytes with 1 <= d < n.
message Message to sign. May be nullptr only if size is zero.
size Message size in bytes.
signature Receives the DER encoded signature (8 to 72 bytes).

Returns: TRUE on success, or FALSE on failure: a key of a wrong size or out of range (the zero scalar, n and larger), a null message with a size, a backend without ECDSA, an uninitialized provider. On failure the signature is empty. The CNG backend derives the public point from the scalar itself.

Ecdsa verify method

The verify(…) method verifies a signature. Method declaration:

static bool verify(const std::vector<uint8_t>& publicKey,
                   const void* message, size_t size,
                   const void* signature, size_t signatureSize);

static bool verify(const std::vector<uint8_t>& publicKey,
                   const std::vector<uint8_t>& message,
                   const std::vector<uint8_t>& signature);
Parameter Value
publicKey Public key: exactly 65 bytes, an uncompressed point on the curve.
message Signed message. May be nullptr only if size is zero.
size Message size in bytes.
signature DER encoded signature. Must not be nullptr.
signatureSize Signature size in bytes (8 to 72).

Returns: TRUE only for a valid signature of this message by this key. FALSE for a wrong signature and for every malformed argument: a key of a wrong size, with a wrong prefix or not on the curve, a signature of a wrong size or in a non-canonical encoding, a null pointer with a size.

Example:

const std::string text = "message";
std::vector<uint8_t> signature;
if (rapidpixel::Ecdsa::sign(privateKey, text.data(), text.size(), signature) &&
    rapidpixel::Ecdsa::verify(publicKey, text.data(), text.size(),
                              signature.data(), signature.size()))
{
    std::cout << "Signature is valid" << std::endl;
}

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 rapidpixel
{

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 = rapidpixel::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 rapidpixel
{

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. Only the canonical encoding is accepted: the bits of the last character that carry no data must be zero, so "Zg==" decodes and "Zh==" is refused. A refusal erases the output vector over its capacity, with the bytes decoded before it, leaves it empty, and says why in CryptoProvider::lastError(). 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; on a refusal erased over its capacity and left empty.

Returns: TRUE on successful decode, or FALSE if input string is invalid or not canonical, with the reason in CryptoProvider::lastError().

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. A refusal erases the output vector over its capacity, with the bytes decoded before it, leaves it empty, and says why in CryptoProvider::lastError(). 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; on a refusal erased over its capacity and left empty.

Returns: TRUE on success, or FALSE on invalid hexadecimal input, with the reason in CryptoProvider::lastError().

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, with the rules of decode method: only the canonical encoding is accepted. 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; on a refusal erased over its capacity and left empty.

Returns: TRUE on success, or FALSE if input is malformed or not canonical, with the reason in CryptoProvider::lastError().

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. A vector or a string is wiped over its whole capacity, not only its size, and keeps its capacity.

The library erases its own copies of keys, passwords and plaintexts, the key schedules, GCM subkeys, HMAC pads, hash states, KDF blocks and keystreams of the standalone backend and those the CNG backend holds, the raw bytes behind hashHex(), finalizeHex(), randomHex() and the HMAC functions that write into a buffer, the input a Cipher collects whenever it outgrows its block, an AES-GCM plaintext that fails its tag and an AES-CBC plaintext that fails its padding; it does not erase the working state inside the block, hash and GHASH functions of the standalone backend, what OpenSSL and CNG keep inside their own objects (theirs to erase), or the earlier content of an output vector the caller passes when the library has to enlarge it.

namespace rapidpixel
{

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 wiped to zero over its whole capacity, not only its size, then cleared; the capacity is kept. A vector with spare capacity is wiped even when it is empty.
text String wiped to zero over its whole capacity, not only its size, then cleared; the capacity is kept.

Returns: None.

Example:

std::vector<uint8_t> secretKey = ...;
rapidpixel::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 wiped to zero over its whole capacity, not only its size, then cleared; the capacity is kept. A vector with spare capacity is wiped even when it is empty.
text String wiped to zero over its whole capacity, not only its size, then cleared; the capacity is kept.

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,          // not declared with CRYPTOPROVIDER_MD5_SHA1 off
    Sha1,         // not declared with CRYPTOPROVIDER_MD5_SHA1 off
    Sha256,
    Sha384,
    Sha512,
    Aes128Ctr,
    Aes128Cbc,
    Aes256Cbc,
    Aes128Gcm,
    Aes256Gcm,
    HmacSha1,     // not declared with CRYPTOPROVIDER_MD5_SHA1 off
    HmacSha256,
    Pbkdf2,
    Hkdf,
    EcdsaP256Sha256,
    Sha224,
    HmacSha224,
    HmacSha384,
    HmacSha512,
    Aes128Cfb,
    Aes192Cfb,
    Aes256Cfb
};
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.
Algo::EcdsaP256Sha256 FIPS 186-5 Yes ECDSA on the NIST P-256 curve with SHA-256 (OpenSSL and CNG backends).
Algo::Sha224 FIPS 180-4 Yes SHA-224 message digest (224-bit). Not in CNG.
Algo::HmacSha224 RFC 2104 / RFC 4231 Yes HMAC with SHA-224 hash. Not in CNG.
Algo::HmacSha384 RFC 2104 / RFC 4231 Yes HMAC with SHA-384 hash.
Algo::HmacSha512 RFC 2104 / RFC 4231 Yes HMAC with SHA-512 hash.
Algo::Aes128Cfb NIST SP 800-38A Yes AES-128 cipher feedback mode, 128-bit feedback (SNMPv3, RFC 3826).
Algo::Aes192Cfb NIST SP 800-38A Yes AES-192 cipher feedback mode, 128-bit feedback.
Algo::Aes256Cfb NIST SP 800-38A Yes AES-256 cipher feedback mode, 128-bit feedback.

With <PARENT>_CRYPTOPROVIDER_MD5_SHA1 off, Algo::Md5, Algo::Sha1 and Algo::HmacSha1 are not declared, so code that names them does not compile; the values after them then have other numbers, which is why an Algo value is never stored or sent as a number.

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): at least 1, with HKDF up to 255 hash blocks (RFC 5869), with PBKDF2 up to INT_MAX; 0 and a larger size are refused.
legacyPkcs5 bool Allow legacy PKCS#5 vectors: in the standard mode PBKDF2 skips the NIST SP 800-132 minimums (CRYPTO_KDF_MIN_ITERATIONS, CRYPTO_KDF_MIN_SALT_SIZE, CRYPTO_KDF_MIN_KEY_SIZE), which are checked when the flag is FALSE. Refused in FIPS mode.

FipsConfig struct

Where the FIPS module comes from and what it has to be, for init method. Used by the OpenSSL backend only. Declared in CryptoProvider.h:

struct FipsConfig
{
    std::string moduleDir;
    std::string configFile;
    std::string requiredVersion;
    bool requireApprovedSettings{false};
    bool ignoreEnvironment{false};
    bool requireTlsEmsCheck{true};
};
Field Type Description
moduleDir std::string Directory holding fips.so. Empty means the OpenSSL default module path.
configFile std::string openssl.cnf that includes fipsmodule.cnf (which carries the module’s integrity MAC) and so activates the module: the activate = 1 that openssl fipsinstall writes into fipsmodule.cnf is required, because the module is brought up by the configuration only and never loaded without it. Empty means the default openssl.cnf. Loaded into the private context only, so OpenSSL’s process-wide default context is unaffected.
requiredVersion std::string Module version the caller accepts, e.g. "3.1.2". Empty accepts any. A CMVP certificate is issued to a module version, not to “the FIPS provider”.
requireApprovedSettings bool Require the approved-mode settings that openssl fipsinstall -pedantic writes into fipsmodule.cnf: security-checks, tls1-prf-ems-check and drbg-no-trunc-md (OpenSSL FIPS provider Security Policy 2.4, 11.1c). A module installed without them loads fine and quietly enforces less.
ignoreEnvironment bool Do not let the environment variables OPENSSL_CONF and OPENSSL_MODULES choose the configuration file and the module directory: an empty configFile or moduleDir then means the location compiled into OpenSSL (a missing default configuration file is not an error of its own: the module then fails to load). For code that must not let the end user replace the FIPS module. A module already in force that the environment located serves no such request: it is refused with FipsError::ModulePathConflict, see init method. The CNG and standalone backends ignore it. OPENSSL_CONF_INCLUDE is not covered: OpenSSL prefixes a relative .include line with it even in a configuration file named in configFile, so a FIPS configuration has to .include by absolute path.
requireTlsEmsCheck bool With requireApprovedSettings, require tls1-prf-ems-check too. That setting governs the TLS 1.2 PRF only (RFC 7627): a product with no TLS sets FALSE, and its module is then judged by the settings that apply to it. No effect without requireApprovedSettings.

FipsError enum

Why a FIPS request was refused, from init method and runFipsSelfTest method. Declared in CryptoProvider.h:

The value “no error” is named FipsError::NoError. The value is not named None because the X11 headers define a macro None.

Value Description
FipsError::NoError No error.
FipsError::NotSupported The backend cannot provide the FIPS module asked for: the standalone backend has none, CNG has no configurable one and runs in FIPS mode only under the Windows system policy.
FipsError::NotActive No FIPS module is in force.
FipsError::ModulePathInvalid Module directory rejected by OpenSSL.
FipsError::ConfigLoadFailed Configuration file missing, malformed, or its .include of fipsmodule.cnf does not resolve.
FipsError::BaseProviderMissing No base provider: key and certificate decoders unavailable.
FipsError::ModuleLoadFailed fips.so absent or unloadable, which includes a failed integrity (MAC) check: OpenSSL reports both the same way. Also a configuration that declares the module without activating it.
FipsError::NotEnforced The FIPS default properties are not enforced on the context, or a provider other than fips and base is active in it (lastError() names it).
FipsError::SelfTestFailed Pre-operational or on-demand self-tests did not pass.
FipsError::SecurityChecksDisabled security-checks off (Security Policy 11.1c forbids disabling it).
FipsError::EmsCheckDisabled tls1-prf-ems-check off: RFC 7627 not enforced for TLS 1.2.
FipsError::TruncDigestAllowed drbg-no-trunc-md off.
FipsError::ModuleVersionMismatch The module is not the required version.
FipsError::ModulePathConflict A FIPS module from other paths is already in force in this process, or the environment located the module in force and the request ignores the environment (lastError() names the variables).
FipsError::InternalError Allocation or OpenSSL API failure.
FipsError::ModeConflict Another mode is already established in this process (the first successful init() fixes the mode for the life of the process), or the operating system requires the FIPS mode and the request is standard.

Constants

Declared in CryptoProvider.h:

constexpr size_t CRYPTO_DIGEST_SIZE_MD5 = 16;    // not declared with CRYPTOPROVIDER_MD5_SHA1 off
constexpr size_t CRYPTO_DIGEST_SIZE_SHA1 = 20;   // not declared with CRYPTOPROVIDER_MD5_SHA1 off
constexpr size_t CRYPTO_DIGEST_SIZE_SHA224 = 28;
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_AES192_KEY_SIZE = 24;
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_GCM_MIN_TAG_SIZE = 12;

constexpr size_t CRYPTO_HMAC_MIN_TRUNCATED_SIZE = 4;

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 size_t CRYPTO_FIPS_MIN_KEY_SIZE = 14;

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;

constexpr size_t CRYPTO_ECDSA_P256_PRIVATE_KEY_SIZE = 32;
constexpr size_t CRYPTO_ECDSA_P256_PUBLIC_KEY_SIZE = 65;
constexpr size_t CRYPTO_ECDSA_P256_MIN_SIGNATURE_SIZE = 8;
constexpr size_t CRYPTO_ECDSA_P256_MAX_SIGNATURE_SIZE = 72;

CRYPTO_GCM_IV_SIZE is the only IV size AES-GCM takes. CRYPTO_GCM_MIN_TAG_SIZE is the shortest GCM tag the raw-pointer overloads of Aead and a GCM Cipher accept (NIST SP 800-38D); the vector forms of Aead take CRYPTO_GCM_TAG_SIZE only. CRYPTO_HMAC_MIN_TRUNCATED_SIZE is the shortest truncated MAC the buffer forms of hmacSha1() and hmacSha256() write (32 bits, NIST SP 800-107). CRYPTO_KDF_MAX_KEY_SIZE is not enforced by the library: it is a bound a caller may hold its own keys to, and Kdf refuses only the key sizes it cannot produce (HKDF above 255 hash blocks, PBKDF2 above INT_MAX bytes, see Kdf class declaration). CRYPTO_FIPS_MIN_KEY_SIZE is the shortest HMAC key and HKDF input keying material the FIPS mode accepts (112 bits, NIST SP 800-131A; see the usage rules in FIPS 140-3 compliance mode); the standard mode does not apply it.

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    |   | OpenSSL       |   | Standalone Custom   |
| CNG (bcrypt.lib)  |   | 3.x           |   | C++ Implementations |
| (Impl/Cng)        |   | (Impl/OpenSsl)|   | (Impl/Custom)       |
+-------------------+   +---------------+   +---------------------+

The diagram shows the AUTO selection: “Linux” stands for every non-Windows system. The OpenSSL backend can be selected on Windows too (see Backend selection option).

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, loads the OpenSSL configuration and the fips and base providers into a private OSSL_LIB_CTX and enables the FIPS default properties; a configuration that activates any other provider in that context is refused. The module and configuration paths default to OpenSSL’s and can be set with FipsConfig, which can also require a module version and the approved-mode settings. FIPS is reported only when that context proves enforcement (SHA2-256 resolves, MD5 does not). A process holds one mode, the module is loaded once per process and never replaced, and a failed on-demand self-test is permanent. When the system flag /proc/sys/crypto/fips_enabled is 1, a standard request is refused, so the application has to ask for the FIPS mode. 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: the FIPS mode is served only while the Windows FIPS policy is on (BCryptGetFipsAlgorithmMode), and MD5 and a standard request are refused then. The CNG primitives are validated by Microsoft, AES-CFB included (CNG’s own CFB mode); AES-CTR, PBKDF2 and HKDF are composed by CryptoProvider from CNG primitives, outside that module, and so is the DER encoding of an ECDSA signature (CNG works with the raw r || s form): the signature itself is made and checked by CNG.
  • Linux without OpenSSL: the standalone implementations are never reported as FIPS: a FIPS request is refused with FipsError::NotSupported, and with FipsError::ModeConflict once the standard mode is established. When the system flag /proc/sys/crypto/fips_enabled is 1, a standard request is refused as well, so such a system cannot be served. They have no ECDSA.

Usage rules of the FIPS mode. isFipsActive() is one indicator for the whole process, the indicator of FIPS 140-3 IG 2.4.C, so in the FIPS mode CryptoProvider refuses a use that does not conform to the Security Policy of the module instead of serving it under that indicator, also where the module itself serves it. isAllowed() answers for the algorithm only; these rules govern how an allowed algorithm is used, and each refusal sets lastError():

  • AES-GCM encryption takes no IV from the caller. The Security Policy of the OpenSSL FIPS provider 3.1.2 (certificate #4985, “AES-GCM Usage”) requires the IV of an encryption to be generated inside the module, at least 96 bits from its approved DRBG (NIST SP 800-38D 8.2.2, FIPS 140-3 IG C.H): “an IV must not be imported for encryption from outside the cryptographic boundary of the Module”. aeadSeal() does so with the OpenSSL backend in both modes; aeadSealWithIv() in every overload and an AES-GCM Cipher for encryption are refused. Decryption with a given IV is served. With CNG aeadSeal() still draws the nonce in the library (BCryptGenRandom) and hands it to the cipher.
  • HMAC keys are at least 112 bits (CRYPTO_FIPS_MIN_KEY_SIZE, 14 bytes). NIST SP 800-131A disallows HMAC generation with a key shorter than 112 bits. The OpenSSL FIPS provider 3.1.2 computes such a MAC all the same (measured), and under the process-wide indicator of IG 2.4.C it would pass for an approved service, so CryptoProvider refuses it: every HMAC call (the Hmac constructors and init(), the one-shot hmac(), hmacSha1(), hmacSha256() and the static Hmac::hmac*()) of every HMAC algorithm (SHA-1, SHA-224, SHA-256, SHA-384, SHA-512) refuses a shorter key, the empty key included. PBKDF2 is not under this rule: its HMAC key is the password, which NIST SP 800-132 governs.
  • HKDF input keying material is at least 112 bits (CRYPTO_FIPS_MIN_KEY_SIZE). A derived key is no stronger than the material it comes from (NIST SP 800-56C, SP 800-131A); the module derives from shorter material all the same (measured), so Kdf::hkdf() and deriveKey() with KdfAlgo::Hkdf refuse it, the empty one included. The HKDF salt, the HMAC key of its extract step, is not under this rule: an empty salt is legal (RFC 5869, NIST SP 800-56C).

A rule reads the mode only once the provider is known ready, and refuses the call before init() with "Crypto backend not initialised". init() publishes the mode before it publishes readiness, so a call racing the first init(Mode::Fips) in another thread is refused, or sees the FIPS mode and obeys the rule; it is never served in the FIPS mode without it.

Physical source exclusion for certification

Only the sources of the selected backend are compiled:

  • On Windows: Custom standalone implementations are excluded from compilation via CMake file filtering, and so are the OpenSSL files with the CNG backend and the CNG files with the OpenSSL backend.
  • 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

cd CryptoProvider

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

# Run the tests of the standard mode (see Tests below for all three groups;
# ./build/bin/Release/CryptoProviderTest with multi-configuration generators such as Visual Studio)
./build/bin/CryptoProviderTest

Option 2: Connect to your project

Copy the folder of the library CryptoProvider to the folder of your project (for example from the folder modules of the RapidPixel SDK). In your project’s CMakeLists.txt:

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

Backend selection option

The backend is chosen with <PARENT>_CRYPTOPROVIDER_BACKEND in the CONFIGURATION block of the top-level CMakeLists.txt, or set by a parent project:

Value Backend
AUTO (default) CNG on Windows; elsewhere OpenSSL when OpenSSL ≥ 3.0 is found, the standalone implementations when not.
OPENSSL OpenSSL ≥ 3.0 (find_package(OpenSSL 3.0 REQUIRED)), on Windows too. The backend to ask for when the OpenSSL FIPS provider is the module to use: on Windows it loads fips.dll. Point CMake at a non-default installation with -DOPENSSL_ROOT_DIR=<prefix>.
CNG Windows CNG; a configuration error elsewhere.
CUSTOM The standalone implementations; a configuration error on Windows. Their AES looks up tables (S-box), so its time depends on the key and the data: where other code on the same computer can measure that time, use OpenSSL.

Stand-alone, an option given on the command line is what the build uses: cmake -B build -D_CRYPTOPROVIDER_BACKEND=OPENSSL. As a sub-repository, the parent decides through <PARENT>_SUBMODULE_CACHE_OVERWRITE. For a build directory whose cache still holds _SUBMODULE_CACHE_OVERWRITE=ON from an earlier configuration, give -D_SUBMODULE_CACHE_OVERWRITE=OFF once, or configure into an empty directory.

MD5 and SHA-1 option

<PARENT>_CRYPTOPROVIDER_MD5_SHA1 (ON by default) decides whether MD5 and SHA-1 exist in the build at all: the digests, HMAC-SHA-1 and PBKDF2-HMAC-SHA1. OFF is for products that must hold no non-approved primitive anywhere in their code:

  • Algo::Md5, Algo::Sha1, Algo::HmacSha1, CRYPTO_DIGEST_SIZE_MD5, CRYPTO_DIGEST_SIZE_SHA1, Digest::md5Hex(), Digest::sha1Hex(), Hmac::hmacSha1(), hmacSha1() and Kdf::pbkdf2Sha1() are not declared, so code that uses them does not compile;
  • the standalone MD5 and SHA-1 sources are not compiled, and no backend implements either algorithm. The OpenSSL backend still names MD5 once, as a request it expects the FIPS module in force to refuse: that is how it checks the module enforces the FIPS properties.

The library defines CRYPTOPROVIDER_NO_MD5_SHA1 as a public compile definition then, so a target that links CryptoProvider sees the same header. A parent sets the option before it adds the library:

SET(${PARENT}_CRYPTOPROVIDER_MD5_SHA1 OFF CACHE BOOL "" FORCE)
add_subdirectory(RapidPixel/CryptoProvider)

The library never forces this option to its default, even when <PARENT>_SUBMODULE_CACHE_OVERWRITE is ON, so a parent’s OFF holds either way.

The library links the library of its backend as a public dependency: bcrypt (CNG) or OpenSSL::Crypto (libcrypto, OpenSSL backend); the standalone backend needs none. A program that links CryptoProvider needs it too; CMake adds it to targets that link CryptoProvider.

On Windows the OpenSSL backend ignores the Windows FIPS policy, which governs the CNG module: the FIPS mode is what the application asks for. The OpenSSL DLLs (libcrypto-3-x64.dll) have to be on PATH at run time.

Tests

A process holds one crypto mode, so the test application runs as three processes, one per group (the fips group starts four more of its own, see below). Each prints a [PASS] or [FAIL] line per check and a summary, and exits with 0 only when every check passes; an unknown group exits with 1.

Command Group
CryptoProviderTest The standard mode, with any backend: known answers, round trips and refusals of every class, and the mode rules: a backend without a loadable module refuses a FIPS request before init() and establishes nothing, and once the standard mode is established a FIPS request is refused with FipsError::ModeConflict. Needs a system that does not require FIPS.
CryptoProviderTest fips The FIPS mode of the OpenSSL backend, on the module located by two environment variables: CRYPTOPROVIDER_FIPS_MODULE_DIR, the directory of fips.so, and CRYPTOPROVIDER_FIPS_CONFIG_FILE, an openssl.cnf that includes the fipsmodule.cnf next to it. The refused requests run first and establish nothing: a missing configuration or module, OPENSSL_CONF naming a missing file, another module version, configurations that activate the default or the null provider next to the module (FipsError::NotEnforced). With CRYPTOPROVIDER_FIPS_NOPEDANTIC_CONFIG_FILE, an openssl.cnf of the same module installed without -pedantic, requireTlsEmsCheck is checked too. Then the module is put in force with requireApprovedSettings and checked, the AES-GCM rules of the FIPS mode are checked under it (the nonce of aeadSeal() generated by the provider, no IV handed to the cipher, encryption with a caller IV refused, decryption with one served), HMAC keys and HKDF input keying material shorter than CRYPTO_FIPS_MIN_KEY_SIZE are refused, the Cipher, Hmac, KDF size, per-thread lastError() and OpenSSL error queue checks of the standard group run again under the module, and a standard request is refused with FipsError::ModeConflict. A request with ignoreEnvironment is served by that module, which the caller’s paths located; the group then runs itself four more times as CryptoProviderTest fips-environment, each in a process of its own with OPENSSL_CONF, OPENSSL_MODULES or both naming the same module: where the environment locates the module in force, a later request with ignoreEnvironment is refused with FipsError::ModulePathConflict and lastError() names the variables; where the loading request names both paths itself, such a request is served. Without the two variables, or with another backend, the group is skipped and passes.
CryptoProviderTest kernel An operating system that requires FIPS, with the OpenSSL and standalone backends on Linux (skipped elsewhere): /proc/sys/crypto/fips_enabled has to read 1. A standard request is refused through both overloads with FipsError::ModeConflict and "the operating system requires the FIPS mode; initialise with Mode::Fips", also with paths that cannot load (no module is looked for), and establishes nothing. With the two variables of the fips group set (OpenSSL backend), a standard request with their module is refused the same way and loads nothing, a FIPS request then puts the module in force, and a later standard request is still refused with the system’s reason. Without them a FIPS request is served by the module the default configuration brings up, or refused with the reason of the module (the standalone backend: FipsError::NotSupported).
# Standard mode
./build/bin/CryptoProviderTest

# FIPS mode, with an OpenSSL FIPS provider installed under /opt/openssl-fips
CRYPTOPROVIDER_FIPS_MODULE_DIR=/opt/openssl-fips/lib/ossl-modules \
CRYPTOPROVIDER_FIPS_CONFIG_FILE=/opt/openssl-fips/ssl/openssl.cnf \
./build/bin/CryptoProviderTest fips

# A kernel that requires FIPS, faked for one process without root
CRYPTOPROVIDER_FIPS_MODULE_DIR=/opt/openssl-fips/lib/ossl-modules \
CRYPTOPROVIDER_FIPS_CONFIG_FILE=/opt/openssl-fips/ssl/openssl.cnf \
unshare -rm sh -c 'mount -t tmpfs none /proc/sys && mkdir /proc/sys/crypto && \
    echo 1 > /proc/sys/crypto/fips_enabled && ./build/bin/CryptoProviderTest kernel'

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 rapidpixel;

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