qb  2.0.0.0
C++17 Actor Framework
qb Issue Watch Star Fork Follow @isndev
Loading...
Searching...
No Matches
qb::crypto Class Reference

Provides cryptographic operations and utilities. More...

#include <crypto.h>

Classes

struct  Argon2Params
 Parameters for the Argon2 algorithm. More...
class  base64
 Base64 encoding and decoding utilities. More...

Public Types

enum class  SymmetricAlgorithm {
  AES_128_CBC , AES_192_CBC , AES_256_CBC , AES_128_GCM ,
  AES_192_GCM , AES_256_GCM , CHACHA20_POLY1305
}
 Supported symmetric cipher algorithms.
enum class  DigestAlgorithm {
  MD5 , SHA1 , SHA224 , SHA256 ,
  SHA384 , SHA512 , BLAKE2B512 , BLAKE2S256
}
 Supported digest algorithms.
enum class  Argon2Variant { Argon2d , Argon2i , Argon2id }
 Variants of the Argon2 algorithm.
enum class  KdfAlgorithm { PBKDF2 , HKDF , Argon2 }
 Key derivation algorithms.
enum class  ECIESMode { STANDARD , AES_GCM , CHACHA20 }
 Operation modes for elliptic curve encryption.
enum class  EnvelopeFormat { RAW , JSON , BASE64 }
 Format for envelope encryption outputs.

Public Member Functions

template<typename T, std::size_t N>
std::string generate_random_string (std::size_t len, const T range[N])
 Generate a random string using characters from the specified array.

Static Public Member Functions

template<typename T = std::mt19937>
static auto random_generator ()
 Create a cryptographically secure random number generator.
template<typename T>
static std::string generate_random_string (std::size_t len, T const &range)
 Generate a random string using characters from the specified range.
static std::string to_hex_string (const std::string &input, std::string_view const &range=range_hex_upper) noexcept
 Convert a binary string to a hexadecimal string.
static int hex_value (unsigned char hex_digit) noexcept
 Get the numeric value of a hexadecimal digit.
static std::string hex_to_string (const std::string &input) noexcept
 Convert a hexadecimal string to a formatted string.
static std::string evp (std::istream &stream, const EVP_MD *md) noexcept
 Calculate a hash from an input stream using a specified digest algorithm.
static std::string md5 (const std::string &input, std::size_t iterations=1) noexcept
 Calculate an MD5 hash of a string.
static std::string md5 (std::istream &stream, std::size_t iterations=1) noexcept
 Calculate an MD5 hash of data from an input stream.
static std::string sha1 (const std::string &input, std::size_t iterations=1) noexcept
 Calculate a SHA-1 hash of a string.
static std::string sha1 (std::istream &stream, std::size_t iterations=1) noexcept
 Calculate a SHA-1 hash of data from an input stream.
static std::string sha256 (const std::string &input, std::size_t iterations=1) noexcept
 Calculate a SHA-256 hash of a string.
static std::string sha256 (std::istream &stream, std::size_t iterations=1) noexcept
 Calculate a SHA-256 hash of data from an input stream.
static std::string sha512 (const std::string &input, std::size_t iterations=1) noexcept
 Calculate a SHA-512 hash of a string.
static std::string sha512 (std::istream &stream, std::size_t iterations=1) noexcept
 Calculate a SHA-512 hash of data from an input stream.
static std::string pbkdf2 (const std::string &password, const std::string &salt, int iterations, int key_size) noexcept
 Derive a key using PBKDF2.
static std::string base64_encode (const unsigned char *data, size_t len)
 Encode binary data to Base64.
static std::vector< unsigned char > base64_decode (const std::string &input)
 Decode a Base64 string to binary data.
static std::vector< unsigned char > hmac_sha256 (const std::vector< unsigned char > &key, const std::string &data)
 Calculate an HMAC-SHA256 hash.
static std::vector< unsigned char > sha256 (const std::vector< unsigned char > &data)
 Calculate a SHA-256 hash of binary data.
static std::vector< unsigned char > xor_bytes (const std::vector< unsigned char > &a, const std::vector< unsigned char > &b)
 XOR two byte arrays.
static std::vector< unsigned char > generate_random_bytes (size_t size)
 Generate cryptographically secure random bytes.
static std::vector< unsigned char > generate_iv (SymmetricAlgorithm algorithm)
 Generate a random initialization vector (IV)
static std::vector< unsigned char > generate_key (SymmetricAlgorithm algorithm)
 Generate a random key.
static std::vector< unsigned char > encrypt (const std::vector< unsigned char > &plaintext, const std::vector< unsigned char > &key, const std::vector< unsigned char > &iv, SymmetricAlgorithm algorithm, const std::vector< unsigned char > &aad={})
 Encrypt data using a symmetric algorithm.
static std::vector< unsigned char > decrypt (const std::vector< unsigned char > &ciphertext, const std::vector< unsigned char > &key, const std::vector< unsigned char > &iv, SymmetricAlgorithm algorithm, const std::vector< unsigned char > &aad={})
 Decrypt data using a symmetric algorithm.
static std::vector< unsigned char > hash (const std::vector< unsigned char > &data, DigestAlgorithm algorithm)
 Compute a generic hash using the specified algorithm.
static std::vector< unsigned char > hmac (const std::vector< unsigned char > &data, const std::vector< unsigned char > &key, DigestAlgorithm algorithm)
 Compute an HMAC using the specified algorithm.
static std::pair< std::string, std::string > generate_rsa_keypair (int bits=2048)
 Generate an RSA key pair.
static std::pair< std::string, std::string > generate_ec_keypair (const std::string &curve="prime256v1")
 Generate an EC key pair.
static std::vector< unsigned char > rsa_sign (const std::vector< unsigned char > &data, const std::string &private_key, DigestAlgorithm digest=DigestAlgorithm::SHA256)
 Sign data using an RSA private key.
static bool rsa_verify (const std::vector< unsigned char > &data, const std::vector< unsigned char > &signature, const std::string &public_key, DigestAlgorithm digest=DigestAlgorithm::SHA256)
 Verify an RSA signature.
static std::vector< unsigned char > ec_sign (const std::vector< unsigned char > &data, const std::string &private_key, DigestAlgorithm digest=DigestAlgorithm::SHA256)
 Sign data using an EC private key.
static bool ec_verify (const std::vector< unsigned char > &data, const std::vector< unsigned char > &signature, const std::string &public_key, DigestAlgorithm digest=DigestAlgorithm::SHA256)
 Verify an EC signature.
static std::vector< unsigned char > ecdh_derive_secret (const std::string &private_key, const std::string &peer_public_key)
 Derive a shared secret using ECDH.
static bool secure_random_fill (std::vector< unsigned char > &buffer)
 Fill a vector with secure random bytes.
static const EVP_MD * get_evp_md (DigestAlgorithm algorithm)
 Convert a digest algorithm enum to its corresponding EVP_MD.
static std::vector< unsigned char > argon2_kdf (const std::string &password, size_t key_length, const Argon2Params &params, Argon2Variant variant=Argon2Variant::Argon2id)
 Key derivation based on Argon2.
static std::vector< unsigned char > hkdf (const std::vector< unsigned char > &input_key_material, const std::vector< unsigned char > &salt, const std::vector< unsigned char > &info, size_t output_length, DigestAlgorithm digest=DigestAlgorithm::SHA256)
 Key derivation with HKDF (HMAC-based Key Derivation Function)
static std::vector< unsigned char > derive_key (const std::string &password, const std::vector< unsigned char > &salt, size_t key_length, KdfAlgorithm algorithm=KdfAlgorithm::Argon2, int iterations=10000, const Argon2Params &argon2_params=Argon2Params())
 High-level function to derive a key from a password.
static std::vector< unsigned char > ecies_encrypt (const std::vector< unsigned char > &plaintext, const std::string &recipient_public_key, ECIESMode mode=ECIESMode::AES_GCM, DigestAlgorithm digest=DigestAlgorithm::SHA256)
 Integrated Elliptic Curve Encryption (ECIES)
static std::vector< unsigned char > ecies_decrypt (const std::vector< unsigned char > &ciphertext, const std::string &private_key, ECIESMode mode=ECIESMode::AES_GCM, DigestAlgorithm digest=DigestAlgorithm::SHA256)
 ECIES decryption.
static std::string envelope_encrypt (const std::vector< unsigned char > &plaintext, const std::string &recipient_public_key, SymmetricAlgorithm algorithm=SymmetricAlgorithm::AES_256_GCM, EnvelopeFormat format=EnvelopeFormat::BASE64)
 Envelope encryption.
static std::vector< unsigned char > envelope_decrypt (const std::string &ciphertext, const std::string &private_key, EnvelopeFormat format=EnvelopeFormat::BASE64)
 Envelope decryption.
static bool constant_time_compare (const std::vector< unsigned char > &a, const std::vector< unsigned char > &b)
 Secure string comparison (resistant to timing attacks)
static std::string generate_token (const std::string &payload, const std::vector< unsigned char > &key, uint64_t ttl=0)
 Generate a secure token with optional TTL.
static std::string verify_token (const std::string &token, const std::vector< unsigned char > &key)
 Verify and decrypt a token.
static std::string base64url_encode (const std::vector< unsigned char > &data)
 Base64URL encode.
static std::vector< unsigned char > base64url_decode (const std::string &input)
 Base64URL decode.
static std::vector< unsigned char > generate_salt (size_t length)
 Generate a secure random salt.
static std::string hash_password (const std::string &password, Argon2Variant variant=Argon2Variant::Argon2id)
 Hash a password securely using Argon2.
static bool verify_password (const std::string &password, const std::string &hash)
 Verify a password against a stored hash.
static std::pair< std::string, std::string > generate_ed25519_keypair ()
 Generate Ed25519 signing key pair.
static std::pair< std::vector< unsigned char >, std::vector< unsigned char > > generate_ed25519_keypair_bytes ()
 Generate Ed25519 keypair returning raw byte vectors.
static std::vector< unsigned char > ed25519_sign (const std::vector< unsigned char > &data, const std::string &private_key)
 Sign data using Ed25519 private key.
static std::vector< unsigned char > ed25519_sign (const std::vector< unsigned char > &data, const std::vector< unsigned char > &private_key)
 Sign data using Ed25519 with raw private key bytes.
static bool ed25519_verify (const std::vector< unsigned char > &data, const std::vector< unsigned char > &signature, const std::string &public_key)
 Verify Ed25519 signature.
static bool ed25519_verify (const std::vector< unsigned char > &data, const std::vector< unsigned char > &signature, const std::vector< unsigned char > &public_key)
 Verify Ed25519 signature with raw public key bytes.
static std::pair< std::string, std::string > generate_x25519_keypair ()
 Generate X25519 key pair for key exchange.
static std::pair< std::vector< unsigned char >, std::vector< unsigned char > > generate_x25519_keypair_bytes ()
 Generate X25519 keypair returning raw byte vectors.
static std::vector< unsigned char > x25519_key_exchange (const std::vector< unsigned char > &private_key, const std::vector< unsigned char > &peer_public_key)
 X25519 key exchange.
static std::vector< unsigned char > x25519_key_exchange (const std::string &private_key_pem, const std::string &peer_public_key_pem)
 X25519 key exchange with PEM keys.
static std::vector< unsigned char > generate_unique_iv (size_t size=12)
 Random initialization vector for one-time use.
static std::string encrypt_with_metadata (const std::vector< unsigned char > &plaintext, const std::vector< unsigned char > &key, const std::string &metadata, SymmetricAlgorithm algorithm=SymmetricAlgorithm::AES_256_GCM)
 Authenticated encryption of data with additional authentication.
static std::optional< std::pair< std::vector< unsigned char >, std::string > > decrypt_with_metadata (const std::string &ciphertext, const std::vector< unsigned char > &key, SymmetricAlgorithm algorithm=SymmetricAlgorithm::AES_256_GCM)
 Decryption and verification of data and metadata integrity.
static std::pair< std::vector< unsigned char >, std::vector< unsigned char > > ecies_encrypt (const std::vector< unsigned char > &data, const std::vector< unsigned char > &recipient_public_key, const std::vector< unsigned char > &optional_shared_info={}, ECIESMode mode=ECIESMode::AES_GCM)
static std::vector< unsigned char > ecies_decrypt (const std::vector< unsigned char > &encrypted_data, const std::vector< unsigned char > &ephemeral_public_key, const std::vector< unsigned char > &recipient_private_key, const std::vector< unsigned char > &optional_shared_info={}, ECIESMode mode=ECIESMode::AES_GCM)

Static Public Attributes

static constexpr const std::string_view range_numeric = "0123456789"
 Character range for numeric values (0-9)
static constexpr const std::string_view range_alpha
 Character range for alphabetic values (A-Z, a-z)
static constexpr const std::string_view range_alpha_lower
 Character range for lowercase alphabetic values (a-z)
static constexpr const std::string_view range_alpha_upper
 Character range for uppercase alphabetic values (A-Z)
static constexpr const std::string_view range_alpha_numeric
 Character range for alphanumeric values (0-9, A-Z, a-z)
static constexpr const std::string_view range_alpha_numeric_special
 Character range for alphanumeric values and special characters.
static constexpr const std::string_view range_hex_upper = "0123456789ABCDEF"
 Character range for uppercase hexadecimal values (0-9, A-F)
static constexpr const std::string_view range_hex_lower = "0123456789abcdef"
 Character range for lowercase hexadecimal values (0-9, a-f)
static constexpr const std::string_view range_byte
 Character range for binary bytes (0-255)

Detailed Description

Provides cryptographic operations and utilities.

This class serves as a container for cryptographic operations including hashing, encoding, encryption, and random string generation. It provides a collection of static methods that can be called directly.

Member Function Documentation

◆ random_generator()

template<typename T = std::mt19937>
auto qb::crypto::random_generator ( )
inlinestatic

Create a cryptographically secure random number generator.

Creates a random number generator of type T (defaulting to mt19937) seeded with a secure random seed sequence.

Template Parameters
TThe type of random number generator to create (default: std::mt19937)
Returns
A securely seeded random number generator

◆ generate_random_string() [1/2]

template<typename T>
std::string qb::crypto::generate_random_string ( std::size_t len,
T const & range )
inlinestatic

Generate a random string using characters from the specified range.

Creates a random string of the specified length using only characters from the provided range.

Template Parameters
TThe type of the character range
Parameters
lenThe length of the random string to generate
rangeThe range of characters to use in the string
Returns
A random string of the specified length

◆ generate_random_string() [2/2]

template<typename T, std::size_t N>
std::string qb::crypto::generate_random_string ( std::size_t len,
const T range[N] )
inline

Generate a random string using characters from the specified array.

Creates a random string of the specified length using only characters from the provided array.

Template Parameters
TThe type of the character array elements
NThe size of the character array
Parameters
lenThe length of the random string to generate
rangeThe array of characters to use in the string
Returns
A random string of the specified length

◆ to_hex_string()

std::string qb::crypto::to_hex_string ( const std::string & input,
std::string_view const & range = range_hex_upper )
staticnoexcept

Convert a binary string to a hexadecimal string.

Converts each byte in the input string to a two-character hexadecimal representation, using characters from the specified range.

Parameters
inputThe binary string to convert
rangeThe range of characters to use for hexadecimal digits (default: uppercase)
Returns
The hexadecimal string representation

◆ hex_value()

int qb::crypto::hex_value ( unsigned char hex_digit)
staticnoexcept

Get the numeric value of a hexadecimal digit.

Converts a hexadecimal digit character to its numeric value (0-15).

Parameters
hex_digitThe hexadecimal digit character
Returns
The numeric value of the digit, or -1 if the character is not a valid hex digit

◆ hex_to_string()

std::string qb::crypto::hex_to_string ( const std::string & input)
staticnoexcept

Convert a hexadecimal string to a formatted string.

Converts a string of hexadecimal bytes to a formatted string representation.

Parameters
inputThe hexadecimal string to convert
Returns
The formatted string

◆ evp()

std::string qb::crypto::evp ( std::istream & stream,
const EVP_MD * md )
staticnoexcept

Calculate a hash from an input stream using a specified digest algorithm.

Computes a cryptographic hash of the data in the input stream using the specified OpenSSL message digest.

Parameters
streamThe input stream containing the data to hash
mdThe OpenSSL message digest to use
Returns
The calculated hash as a hexadecimal string

◆ md5() [1/2]

std::string qb::crypto::md5 ( const std::string & input,
std::size_t iterations = 1 )
staticnoexcept

Calculate an MD5 hash of a string.

Computes the MD5 hash of the input string, optionally applying the hash function multiple times for extra security.

Parameters
inputThe string to hash
iterationsNumber of times to apply the hash function (default: 1)
Returns
The MD5 hash as a hexadecimal string

◆ md5() [2/2]

std::string qb::crypto::md5 ( std::istream & stream,
std::size_t iterations = 1 )
staticnoexcept

Calculate an MD5 hash of data from an input stream.

Computes the MD5 hash of the data in the input stream, optionally applying the hash function multiple times for extra security.

Parameters
streamThe input stream containing the data to hash
iterationsNumber of times to apply the hash function (default: 1)
Returns
The MD5 hash as a hexadecimal string

◆ sha1() [1/2]

std::string qb::crypto::sha1 ( const std::string & input,
std::size_t iterations = 1 )
staticnoexcept

Calculate a SHA-1 hash of a string.

Computes the SHA-1 hash of the input string, optionally applying the hash function multiple times for extra security.

Parameters
inputThe string to hash
iterationsNumber of times to apply the hash function (default: 1)
Returns
The SHA-1 hash as a hexadecimal string

◆ sha1() [2/2]

std::string qb::crypto::sha1 ( std::istream & stream,
std::size_t iterations = 1 )
staticnoexcept

Calculate a SHA-1 hash of data from an input stream.

Computes the SHA-1 hash of the data in the input stream, optionally applying the hash function multiple times for extra security.

Parameters
streamThe input stream containing the data to hash
iterationsNumber of times to apply the hash function (default: 1)
Returns
The SHA-1 hash as a hexadecimal string

◆ sha256() [1/3]

std::string qb::crypto::sha256 ( const std::string & input,
std::size_t iterations = 1 )
staticnoexcept

Calculate a SHA-256 hash of a string.

Computes the SHA-256 hash of the input string, optionally applying the hash function multiple times for extra security.

Parameters
inputThe string to hash
iterationsNumber of times to apply the hash function (default: 1)
Returns
The SHA-256 hash as a hexadecimal string

◆ sha256() [2/3]

std::string qb::crypto::sha256 ( std::istream & stream,
std::size_t iterations = 1 )
staticnoexcept

Calculate a SHA-256 hash of data from an input stream.

Computes the SHA-256 hash of the data in the input stream, optionally applying the hash function multiple times for extra security.

Parameters
streamThe input stream containing the data to hash
iterationsNumber of times to apply the hash function (default: 1)
Returns
The SHA-256 hash as a hexadecimal string

◆ sha512() [1/2]

std::string qb::crypto::sha512 ( const std::string & input,
std::size_t iterations = 1 )
staticnoexcept

Calculate a SHA-512 hash of a string.

Computes the SHA-512 hash of the input string, optionally applying the hash function multiple times for extra security.

Parameters
inputThe string to hash
iterationsNumber of times to apply the hash function (default: 1)
Returns
The SHA-512 hash as a hexadecimal string

◆ sha512() [2/2]

std::string qb::crypto::sha512 ( std::istream & stream,
std::size_t iterations = 1 )
staticnoexcept

Calculate a SHA-512 hash of data from an input stream.

Computes the SHA-512 hash of the data in the input stream, optionally applying the hash function multiple times for extra security.

Parameters
streamThe input stream containing the data to hash
iterationsNumber of times to apply the hash function (default: 1)
Returns
The SHA-512 hash as a hexadecimal string

◆ pbkdf2()

std::string qb::crypto::pbkdf2 ( const std::string & password,
const std::string & salt,
int iterations,
int key_size )
staticnoexcept

Derive a key using PBKDF2.

Uses the PBKDF2 (Password-Based Key Derivation Function 2) algorithm to derive a key from a password and salt.

Parameters
passwordThe password to derive the key from
saltThe salt to use in the derivation process
iterationsNumber of iterations to use in the derivation
key_sizeSize of the derived key in bytes
Returns
The derived key as a string

◆ base64_encode()

std::string qb::crypto::base64_encode ( const unsigned char * data,
size_t len )
static

Encode binary data to Base64.

Converts binary data to a Base64-encoded string. This method does not include newline characters in the output.

Parameters
dataPointer to the binary data to encode
lenLength of the binary data in bytes
Returns
The Base64-encoded string

◆ base64_decode()

std::vector< unsigned char > qb::crypto::base64_decode ( const std::string & input)
static

Decode a Base64 string to binary data.

Converts a Base64-encoded string back to its original binary form.

Parameters
inputThe Base64-encoded string to decode
Returns
The decoded binary data as a vector of unsigned chars

◆ hmac_sha256()

std::vector< unsigned char > qb::crypto::hmac_sha256 ( const std::vector< unsigned char > & key,
const std::string & data )
static

Calculate an HMAC-SHA256 hash.

Computes an HMAC-SHA256 hash of the input data using the provided key.

Parameters
keyThe key to use for the HMAC computation
dataThe data to hash
Returns
The HMAC-SHA256 hash as a vector of unsigned chars

◆ sha256() [3/3]

std::vector< unsigned char > qb::crypto::sha256 ( const std::vector< unsigned char > & data)
static

Calculate a SHA-256 hash of binary data.

Computes the SHA-256 hash of the input binary data.

Parameters
dataThe binary data to hash
Returns
The SHA-256 hash as a vector of unsigned chars

◆ xor_bytes()

std::vector< unsigned char > qb::crypto::xor_bytes ( const std::vector< unsigned char > & a,
const std::vector< unsigned char > & b )
static

XOR two byte arrays.

Performs a bitwise XOR operation between corresponding bytes of two arrays.

Parameters
aThe first byte array
bThe second byte array
Returns
The result of XORing the two arrays
Exceptions
std::runtime_errorif the arrays have different sizes

◆ generate_random_bytes()

std::vector< unsigned char > qb::crypto::generate_random_bytes ( size_t size)
static

Generate cryptographically secure random bytes.

Uses OpenSSL's RAND_bytes to generate secure random bytes.

Parameters
sizeNumber of random bytes to generate
Returns
Vector containing the random bytes

◆ generate_iv()

std::vector< unsigned char > qb::crypto::generate_iv ( SymmetricAlgorithm algorithm)
static

Generate a random initialization vector (IV)

Creates an IV of appropriate size for the specified algorithm.

Parameters
algorithmThe symmetric algorithm for which to generate the IV
Returns
Vector containing the random IV

◆ generate_key()

std::vector< unsigned char > qb::crypto::generate_key ( SymmetricAlgorithm algorithm)
static

Generate a random key.

Creates a key of appropriate size for the specified algorithm.

Parameters
algorithmThe symmetric algorithm for which to generate the key
Returns
Vector containing the random key

◆ encrypt()

std::vector< unsigned char > qb::crypto::encrypt ( const std::vector< unsigned char > & plaintext,
const std::vector< unsigned char > & key,
const std::vector< unsigned char > & iv,
SymmetricAlgorithm algorithm,
const std::vector< unsigned char > & aad = {} )
static

Encrypt data using a symmetric algorithm.

Encrypts the provided data using the specified algorithm, key, and IV. For GCM mode, also computes and appends an authentication tag.

Parameters
plaintextThe data to encrypt
keyThe encryption key
ivThe initialization vector
algorithmThe encryption algorithm to use
aadAdditional authenticated data (for AEAD modes like GCM)
Returns
Vector containing the encrypted data

◆ decrypt()

std::vector< unsigned char > qb::crypto::decrypt ( const std::vector< unsigned char > & ciphertext,
const std::vector< unsigned char > & key,
const std::vector< unsigned char > & iv,
SymmetricAlgorithm algorithm,
const std::vector< unsigned char > & aad = {} )
static

Decrypt data using a symmetric algorithm.

Decrypts the provided data using the specified algorithm, key, and IV. For GCM mode, also verifies the authentication tag.

Parameters
ciphertextThe data to decrypt
keyThe decryption key
ivThe initialization vector
algorithmThe encryption algorithm that was used
aadAdditional authenticated data (for AEAD modes like GCM)
Returns
Vector containing the decrypted data or empty if authentication fails

◆ hash()

std::vector< unsigned char > qb::crypto::hash ( const std::vector< unsigned char > & data,
DigestAlgorithm algorithm )
static

Compute a generic hash using the specified algorithm.

Parameters
dataThe data to hash
algorithmThe hash algorithm to use
Returns
Vector containing the hash

◆ hmac()

std::vector< unsigned char > qb::crypto::hmac ( const std::vector< unsigned char > & data,
const std::vector< unsigned char > & key,
DigestAlgorithm algorithm )
static

Compute an HMAC using the specified algorithm.

Parameters
dataThe data to authenticate
keyThe authentication key
algorithmThe hash algorithm to use
Returns
Vector containing the HMAC

◆ generate_rsa_keypair()

std::pair< std::string, std::string > qb::crypto::generate_rsa_keypair ( int bits = 2048)
static

Generate an RSA key pair.

Parameters
bitsThe key size in bits (e.g., 2048, 3072, 4096)
Returns
Pair of strings containing PEM-encoded private and public keys

◆ generate_ec_keypair()

std::pair< std::string, std::string > qb::crypto::generate_ec_keypair ( const std::string & curve = "prime256v1")
static

Generate an EC key pair.

Parameters
curveThe curve name (e.g., "prime256v1", "secp384r1", "secp521r1")
Returns
Pair of strings containing PEM-encoded private and public keys

◆ rsa_sign()

std::vector< unsigned char > qb::crypto::rsa_sign ( const std::vector< unsigned char > & data,
const std::string & private_key,
DigestAlgorithm digest = DigestAlgorithm::SHA256 )
static

Sign data using an RSA private key.

Parameters
dataThe data to sign
private_keyPEM-encoded private key
digestThe digest algorithm to use
Returns
Vector containing the signature

◆ rsa_verify()

bool qb::crypto::rsa_verify ( const std::vector< unsigned char > & data,
const std::vector< unsigned char > & signature,
const std::string & public_key,
DigestAlgorithm digest = DigestAlgorithm::SHA256 )
static

Verify an RSA signature.

Parameters
dataThe data that was signed
signatureThe signature to verify
public_keyPEM-encoded public key
digestThe digest algorithm that was used
Returns
True if the signature is valid

◆ ec_sign()

std::vector< unsigned char > qb::crypto::ec_sign ( const std::vector< unsigned char > & data,
const std::string & private_key,
DigestAlgorithm digest = DigestAlgorithm::SHA256 )
static

Sign data using an EC private key.

Parameters
dataThe data to sign
private_keyPEM-encoded private key
digestThe digest algorithm to use
Returns
Vector containing the signature

◆ ec_verify()

bool qb::crypto::ec_verify ( const std::vector< unsigned char > & data,
const std::vector< unsigned char > & signature,
const std::string & public_key,
DigestAlgorithm digest = DigestAlgorithm::SHA256 )
static

Verify an EC signature.

Parameters
dataThe data that was signed
signatureThe signature to verify
public_keyPEM-encoded public key
digestThe digest algorithm that was used
Returns
True if the signature is valid

◆ ecdh_derive_secret()

std::vector< unsigned char > qb::crypto::ecdh_derive_secret ( const std::string & private_key,
const std::string & peer_public_key )
static

Derive a shared secret using ECDH.

Parameters
private_keyPEM-encoded EC private key
peer_public_keyPEM-encoded EC public key
Returns
Vector containing the shared secret

◆ secure_random_fill()

bool qb::crypto::secure_random_fill ( std::vector< unsigned char > & buffer)
static

Fill a vector with secure random bytes.

Parameters
bufferThe vector to fill
Returns
True if successful

◆ get_evp_md()

const EVP_MD * qb::crypto::get_evp_md ( DigestAlgorithm algorithm)
static

Convert a digest algorithm enum to its corresponding EVP_MD.

Parameters
algorithmThe digest algorithm
Returns
Pointer to the EVP_MD structure

◆ argon2_kdf()

std::vector< unsigned char > qb::crypto::argon2_kdf ( const std::string & password,
size_t key_length,
const Argon2Params & params,
Argon2Variant variant = Argon2Variant::Argon2id )
static

Key derivation based on Argon2.

Implements the Argon2 algorithm (2id by default) to derive a secure key from a password. Argon2 is designed to be resistant to dedicated hardware attacks by using a large amount of memory and parallel operations.

Parameters
passwordInput password
key_lengthLength of the key to generate (in bytes)
paramsParameters for the Argon2 algorithm
variantArgon2 variant to use
Returns
The derived key

◆ hkdf()

std::vector< unsigned char > qb::crypto::hkdf ( const std::vector< unsigned char > & input_key_material,
const std::vector< unsigned char > & salt,
const std::vector< unsigned char > & info,
size_t output_length,
DigestAlgorithm digest = DigestAlgorithm::SHA256 )
static

Key derivation with HKDF (HMAC-based Key Derivation Function)

Implements HKDF according to RFC 5869 to derive one or more keys from input key material. HKDF is particularly useful for extracting entropy from a non-uniform source and extending it to the desired size.

Parameters
input_key_materialInput key material
saltOptional salt for the extraction step
infoContextual information for the expansion step
output_lengthLength of the key to generate
digestHash algorithm to use
Returns
The derived key

◆ derive_key()

std::vector< unsigned char > qb::crypto::derive_key ( const std::string & password,
const std::vector< unsigned char > & salt,
size_t key_length,
KdfAlgorithm algorithm = KdfAlgorithm::Argon2,
int iterations = 10000,
const Argon2Params & argon2_params = Argon2Params() )
static

High-level function to derive a key from a password.

Provides a unified interface for different key derivation algorithms. Recommendations:

  • For passwords: Argon2
  • For deriving additional keys from an existing key: HKDF
  • For compatibility with existing systems: PBKDF2
Parameters
passwordPassword or input key
saltSalt for derivation
key_lengthLength of the key to generate
algorithmDerivation algorithm to use
iterationsNumber of iterations (for PBKDF2)
argon2_paramsParameters for Argon2 (ignored if another algorithm is used)
Returns
The derived key

◆ ecies_encrypt()

std::vector< unsigned char > qb::crypto::ecies_encrypt ( const std::vector< unsigned char > & plaintext,
const std::string & recipient_public_key,
ECIESMode mode = ECIESMode::AES_GCM,
DigestAlgorithm digest = DigestAlgorithm::SHA256 )
static

Integrated Elliptic Curve Encryption (ECIES)

Implements ECIES (Elliptic Curve Integrated Encryption Scheme), which combines public key cryptography using elliptic curves and symmetric encryption to provide a secure hybrid system.

Parameters
plaintextData to encrypt
recipient_public_keyRecipient's public key (PEM)
modeECIES operation mode
digestHash algorithm to use
Returns
Encrypted data

◆ ecies_decrypt()

std::vector< unsigned char > qb::crypto::ecies_decrypt ( const std::vector< unsigned char > & ciphertext,
const std::string & private_key,
ECIESMode mode = ECIESMode::AES_GCM,
DigestAlgorithm digest = DigestAlgorithm::SHA256 )
static

ECIES decryption.

Decrypts data encrypted with ECIES.

Parameters
ciphertextEncrypted data
private_keyRecipient's private key (PEM)
modeECIES operation mode used for encryption
digestHash algorithm used for encryption
Returns
Decrypted data or empty vector on failure

◆ envelope_encrypt()

std::string qb::crypto::envelope_encrypt ( const std::vector< unsigned char > & plaintext,
const std::string & recipient_public_key,
SymmetricAlgorithm algorithm = SymmetricAlgorithm::AES_256_GCM,
EnvelopeFormat format = EnvelopeFormat::BASE64 )
static

Envelope encryption.

Implements envelope encryption: a symmetric key is generated, used to encrypt the data, and then itself encrypted with a public key. This method is more efficient than ECIES for large volumes of data.

Parameters
plaintextData to encrypt
recipient_public_keyRecipient's public key (PEM)
algorithmSymmetric algorithm to use
formatOutput format for encrypted data
Returns
Encrypted data in the specified format

◆ envelope_decrypt()

std::vector< unsigned char > qb::crypto::envelope_decrypt ( const std::string & ciphertext,
const std::string & private_key,
EnvelopeFormat format = EnvelopeFormat::BASE64 )
static

Envelope decryption.

Decrypts data encrypted with envelope encryption.

Parameters
ciphertextEncrypted data
private_keyRecipient's private key (PEM)
formatFormat of the encrypted data
Returns
Decrypted data or empty vector on failure

◆ constant_time_compare()

bool qb::crypto::constant_time_compare ( const std::vector< unsigned char > & a,
const std::vector< unsigned char > & b )
static

Secure string comparison (resistant to timing attacks)

Compares two byte strings in constant time to avoid information leaks through execution time analysis attacks.

Parameters
aFirst string
bSecond string
Returns
True if the strings are identical, false otherwise

◆ generate_token()

std::string qb::crypto::generate_token ( const std::string & payload,
const std::vector< unsigned char > & key,
uint64_t ttl = 0 )
static

Generate a secure token with optional TTL.

Creates a token containing the specified payload, encrypted and authenticated. The token can optionally include an expiration time.

Parameters
payloadThe payload to include in the token
keyThe key to use for encryption
ttlTime to live in seconds (0 = no expiration)
Returns
The generated token

◆ verify_token()

std::string qb::crypto::verify_token ( const std::string & token,
const std::vector< unsigned char > & key )
static

Verify and decrypt a token.

Verifies the token's authenticity and expiration time, and returns the payload. Returns an empty string if the token is invalid or expired.

Parameters
tokenThe token to verify
keyThe key used for encryption
Returns
The payload or empty string if invalid/expired

◆ base64url_encode()

std::string qb::crypto::base64url_encode ( const std::vector< unsigned char > & data)
static

Base64URL encode.

Encodes data using Base64URL (a variant of Base64 that is safe for use in URLs and filenames).

Parameters
dataThe data to encode
Returns
Base64URL encoded string

◆ base64url_decode()

std::vector< unsigned char > qb::crypto::base64url_decode ( const std::string & input)
static

Base64URL decode.

Decodes data from Base64URL format.

Parameters
inputThe Base64URL encoded string
Returns
Decoded data

◆ generate_salt()

std::vector< unsigned char > qb::crypto::generate_salt ( size_t length)
static

Generate a secure random salt.

Parameters
lengthLength of the salt in bytes
Returns
The generated salt

◆ hash_password()

std::string qb::crypto::hash_password ( const std::string & password,
Argon2Variant variant = Argon2Variant::Argon2id )
static

Hash a password securely using Argon2.

Parameters
passwordThe password to hash
variantArgon2 variant to use
Returns
String containing the formatted hash with parameters

◆ verify_password()

bool qb::crypto::verify_password ( const std::string & password,
const std::string & hash )
static

Verify a password against a stored hash.

Parameters
passwordThe password to verify
hashThe stored hash
Returns
True if the password matches the hash

◆ generate_ed25519_keypair()

std::pair< std::string, std::string > qb::crypto::generate_ed25519_keypair ( )
static

Generate Ed25519 signing key pair.

Generates an Ed25519 signing key pair, designed for speed and security.

Returns
Pair of PEM-encoded strings (private key, public key).

◆ generate_ed25519_keypair_bytes()

std::pair< std::vector< unsigned char >, std::vector< unsigned char > > qb::crypto::generate_ed25519_keypair_bytes ( )
static

Generate Ed25519 keypair returning raw byte vectors.

Returns
Paire de clés au format PEM (privée, publique)

◆ ed25519_sign() [1/2]

std::vector< unsigned char > qb::crypto::ed25519_sign ( const std::vector< unsigned char > & data,
const std::string & private_key )
static

Sign data using Ed25519 private key.

Signs data with the Ed25519 algorithm using a PEM-encoded private key.

Parameters
dataData to sign.
private_keyEd25519 private key in PEM format.
Returns
Signature bytes.

◆ ed25519_sign() [2/2]

std::vector< unsigned char > qb::crypto::ed25519_sign ( const std::vector< unsigned char > & data,
const std::vector< unsigned char > & private_key )
static

Sign data using Ed25519 with raw private key bytes.

Signe des données avec l'algorithme Ed25519.

Parameters
dataDonnées à signer
private_keyClé privée Ed25519 au format PEM
Returns
Signature

◆ ed25519_verify() [1/2]

bool qb::crypto::ed25519_verify ( const std::vector< unsigned char > & data,
const std::vector< unsigned char > & signature,
const std::string & public_key )
static

Verify Ed25519 signature.

Verifies an Ed25519 signature using a PEM-encoded public key.

Parameters
dataData that was signed.
signatureSignature to verify.
public_keyEd25519 public key in PEM format.
Returns
True if the signature is valid.

◆ ed25519_verify() [2/2]

bool qb::crypto::ed25519_verify ( const std::vector< unsigned char > & data,
const std::vector< unsigned char > & signature,
const std::vector< unsigned char > & public_key )
static

Verify Ed25519 signature with raw public key bytes.

Vérifie une signature Ed25519.

Parameters
dataDonnées qui ont été signées
signatureSignature à vérifier
public_keyClé publique Ed25519 au format PEM
Returns
Vrai si la signature est valide

◆ generate_x25519_keypair()

std::pair< std::string, std::string > qb::crypto::generate_x25519_keypair ( )
static

Generate X25519 key pair for key exchange.

Generates an X25519 key pair for Elliptic Curve Diffie-Hellman (ECDH) key exchange.

Returns
Pair of PEM-encoded strings (private key, public key).

◆ generate_x25519_keypair_bytes()

std::pair< std::vector< unsigned char >, std::vector< unsigned char > > qb::crypto::generate_x25519_keypair_bytes ( )
static

Generate X25519 keypair returning raw byte vectors.

Génère une paire de clés X25519 pour l'échange de clés Diffie-Hellman sur courbe elliptique.

Returns
Paire de clés au format PEM (privée, publique)

◆ x25519_key_exchange() [1/2]

std::vector< unsigned char > qb::crypto::x25519_key_exchange ( const std::vector< unsigned char > & private_key,
const std::vector< unsigned char > & peer_public_key )
static

X25519 key exchange.

Derives a shared secret using the X25519 algorithm.

Parameters
private_keyX25519 private key in vector format
peer_public_keyPeer's public key in vector format
Returns
Shared secret

◆ x25519_key_exchange() [2/2]

std::vector< unsigned char > qb::crypto::x25519_key_exchange ( const std::string & private_key_pem,
const std::string & peer_public_key_pem )
static

X25519 key exchange with PEM keys.

Derives a shared secret using the X25519 algorithm.

Parameters
private_key_pemX25519 private key in PEM format
peer_public_key_pemPeer's public key in PEM format
Returns
Shared secret

◆ generate_unique_iv()

std::vector< unsigned char > qb::crypto::generate_unique_iv ( size_t size = 12)
static

Random initialization vector for one-time use.

Generates a random initialization vector guaranteed to be unique, by including a counter and timestamp to avoid duplicates.

Parameters
sizeSize of the initialization vector in bytes
Returns
One-time use IV

◆ encrypt_with_metadata()

std::string qb::crypto::encrypt_with_metadata ( const std::vector< unsigned char > & plaintext,
const std::vector< unsigned char > & key,
const std::string & metadata,
SymmetricAlgorithm algorithm = SymmetricAlgorithm::AES_256_GCM )
static

Authenticated encryption of data with additional authentication.

Encrypts data with authentication, adding metadata protected by integrity (e.g., user ID, timestamp). The metadata is included in the AAD for authenticated encryption.

Parameters
plaintextData to encrypt
keyEncryption key
metadataMetadata to protect (not encrypted but authenticated)
algorithmAlgorithm to use
Returns
Encrypted data (with IV, AAD and tag) in structured format

◆ decrypt_with_metadata()

std::optional< std::pair< std::vector< unsigned char >, std::string > > qb::crypto::decrypt_with_metadata ( const std::string & ciphertext,
const std::vector< unsigned char > & key,
SymmetricAlgorithm algorithm = SymmetricAlgorithm::AES_256_GCM )
static

Decryption and verification of data and metadata integrity.

Decrypts data protected by encrypt_with_metadata and verifies the integrity of the metadata.

Parameters
ciphertextStructured encrypted data
keyDecryption key
algorithmAlgorithm used for encryption
Returns
Structure containing the decrypted data and verified metadata, or empty optional value if authentication fails

Member Data Documentation

◆ range_alpha

const std::string_view qb::crypto::range_alpha
staticconstexpr
Initial value:
= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"

Character range for alphabetic values (A-Z, a-z)

◆ range_alpha_lower

const std::string_view qb::crypto::range_alpha_lower
staticconstexpr
Initial value:
=
"abcdefghijklmnopqrstuvwxyz"

Character range for lowercase alphabetic values (a-z)

◆ range_alpha_upper

const std::string_view qb::crypto::range_alpha_upper
staticconstexpr
Initial value:
=
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"

Character range for uppercase alphabetic values (A-Z)

◆ range_alpha_numeric

const std::string_view qb::crypto::range_alpha_numeric
staticconstexpr
Initial value:
=
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"

Character range for alphanumeric values (0-9, A-Z, a-z)

◆ range_alpha_numeric_special

const std::string_view qb::crypto::range_alpha_numeric_special
staticconstexpr
Initial value:
=
"0123456789"
" !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"

Character range for alphanumeric values and special characters.

◆ range_byte

const std::string_view qb::crypto::range_byte
staticconstexpr
Initial value:
=
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"
"\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F"
"\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F"
"\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F"
"\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F"
"\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F"
"\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F"
"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F"
"\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F"
"\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF"
"\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF"
"\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF"
"\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF"
"\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF"
"\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"

Character range for binary bytes (0-255)