Authenticated encryption (ChaCha20-Poly1305) and key derivation (HMAC-SHA-256, HKDF).
Encryption alone protects nothing useful. An attacker who cannot read a message can still change its bytes, and in a stream cipher, which is what networks use, flipping a bit of the cipher text flips the same bit of the plain text. Without authentication the receiver accepts the changed message as legitimate.
So the interface here is encrypt and authenticate. ICipher::Decrypt returns false when the tag does not match, and in that case it returns no plain text at all. There is no way to ask for decryption without the check.
What this library implements: CChaCha20Poly1305, from RFC 8439, checked against the test vectors of the RFC itself. ChaCha20 is additions, XOR and rotations over a fixed state, with no lookup table and no branch that depends on the secret, so it is free of the timing attacks that affect AES in software.
What it does not implement: key agreement. No RSA, no elliptic curve key exchange, no Diffie-Hellman. That part has subtle failure modes that no test catches, and the right answer is an audited library. The key arrives ready at this layer.
A test vector proves that for those inputs the output is the one the standard requires, which catches rotation, byte order, padding and reduction errors. It does not prove constant time under your compiler and options, resistance to fault attacks, or that the key did not leak some other way. For a product where that matters, replace this implementation with an audited one. ICipher exists so that the swap takes about twenty lines.
bool ConstantTimeEquals( std::span< conststd::uint8_t > A, std::span< conststd::uint8_t > B ) noexcept;
Compares two blocks without leaking where they differ.
A memcmp stops at the first different byte, and the time it takes tells how many bytes matched. When comparing an authentication tag, that lets an attacker find it one byte at a time: try 256 values for the first byte, see which one took longer, keep it, and move on. That is 16 x 256 attempts instead of 2^128.
This function always reads every byte and accumulates the differences with OR.
A
First block.
B
Second block.
true when both have the same size and the same bytes.
Wipes a block of memory in a way the compiler cannot remove.
A memset over memory that nobody reads again is dead code, and the optimizer is allowed to remove it, leaving the key on the stack. This is known and documented compiler behavior, not a compiler defect.
A keyed message authenticator. It is here because key derivation needs it, and because a hash of the key concatenated with the message is not an HMAC. A raw SHA-256 allows extending the message without knowing the key, and whoever trusts that construction as an HMAC inherits the weakness.
Stretches a uniform key into as many keys as needed, each bound to a different label.
This is what makes two keys derived from the same secret independent. Deriving by concatenation with a label looks the same and is not: without the HKDF construction there is no guarantee that knowing one key does not help find the other.
Prk
The pseudorandom key from HkdfExtract.
Info
The label. Different labels give independent keys.
OutKey
Where to write. Up to 8160 bytes.
false when OutKey is larger than the construction allows.
This is the swap point. Whoever wants an audited implementation, such as libsodium, BearSSL or mbedTLS, writes a class derived from this one and installs it. Nothing else in the product changes.
Single use value. Reusing it with the same key destroys the security completely. See the warning in Ethereal::Network::CSecureTransform.
AssociatedData
Authenticated but not encrypted. This is where data that must be readable in clear and still cannot be changed goes: a routing header, a connection identifier.
PlainText
The data to encrypt.
OutCipherText
Receives the cipher text followed by the tag, that is PlainText.size() + TagSize bytes.
false when there is no key or the nonce has the wrong size.
The tag is checked before any plain text is returned. Returning the decrypted data and only then reporting a mismatch is the classic way to turn an authenticated cipher into one that authenticates nothing: the caller has already used the data.
Nonce
Single use value, the one used to encrypt.
AssociatedData
The associated data, the same used to encrypt.
CipherText
Cipher text followed by the tag.
OutPlainText
Receives the plain text.
false when the tag does not match. OutPlainText is left empty.
32 bytes, and truly single use: reusing it with different messages reveals the inner key and allows forgery.
Message
The authenticated message.
OutTag
Receives the 16 byte tag.
aes.hpp
#include <ethereal/cpp/cryptography/aes.hpp>
AES block encryption (FIPS 197) and AES-GCM (NIST SP 800-38D).
Two paths with the same bytes, chosen at run time when the key is installed:
Constant time scalar code. AES is bitsliced (four blocks per pass over eight 64 bit words, the S-box as a Boolean circuit) and GHASH multiplies with integer products masked so that no carry crosses between bits. No table is indexed by a secret and no branch depends on one. The technique is the one of BearSSL aes_ct64 and ghash_ctmul64.
AES-NI and PCLMULQDQ, when Ethereal::Cpu::AesClmulActive says so. Hardware AES has no table either.
Only encryption of the block cipher is offered: GCM uses the forward direction for both encryption and decryption.
AES in Galois/Counter Mode, with a 96 bit nonce and a 128 bit tag.
classCAesGcmfinal : publicICipher
The AEAD of TLS 1.3 (TLS_AES_128_GCM_SHA256 and TLS_AES_256_GCM_SHA384). The key size is fixed at construction: 16 (AES-128-GCM), 24 or 32 (AES-256-GCM).
Decryption checks the tag first, over the cipher text, and only then decrypts. On a mismatch no plain text is produced. The tag comparison is constant time.
Limits of SP 800-38D: at most 2^36 - 32 bytes of text per call. The nonce must never repeat under the same key.
Thread safety: Encrypt and Decrypt do not change the object and may run in several threads at once with the same key. SetKey may not run concurrently with anything.
structCRC32
{
/// @brief Computes the CRC32 (IEEE 802.3) of a binary buffer./// Processes the data byte by byte with a CRC32 table compatible with the IEEE 802.3 standard./// The computation uses the initial value 0xFFFFFFFF and the standard final XOR.////// @param Data Input binary buffer.////// @return Computed CRC32 value.///staticstd::uint32_t Get( std::span<conststd::uint8_t> Data );
/// @brief Computes the CRC32 (IEEE 802.3) of a string./// Views the string as binary data without a copy and computes the CRC32 over those bytes.////// @param Str Input string.////// @return Computed CRC32 value.///staticstd::uint32_t Get( constchar * Str );
/// @brief Computes the CRC32 and writes the value as hexadecimal (lowercase)./// The CRC32 value is written to the output string as 8 lowercase hexadecimal digits, most significant first, like printf( "%08x" ), on any machine./// Does not allocate a return value.////// @param Str Input string./// @param StrOut Output string that receives the CRC in hexadecimal.///staticvoid GetAs_String( constchar * Str, std::string & StrOut );
};
structCRC64
{
/// @brief Computes the CRC64 (ECMA-182) of a binary buffer./// Processes the data byte by byte with a CRC64 table compatible with the ECMA-182 standard./// This algorithm uses no initial XOR and no final XOR.////// @param Data Input binary buffer.////// @return Computed CRC64 value.///staticstd::uint64_t Get( std::span<conststd::uint8_t> Data );
/// @brief Computes the CRC64 (ECMA-182) of a string./// Views the string as binary data without a copy and computes the CRC64 over those bytes.////// @param Str Input string.////// @return Computed CRC64 value.///staticstd::uint64_t Get( constchar * Str );
/// @brief Computes the CRC64 and writes the value as hexadecimal (lowercase)./// The CRC64 value is written to the output string as 16 lowercase hexadecimal digits, most significant first, like printf( "%016llx" ), on any machine./// Does not allocate a return value.////// @param Str Input string./// @param StrOut Output string that receives the CRC in hexadecimal.///staticvoid GetAs_String( constchar * Str, std::string & StrOut );
};
ecc.hpp
#include <ethereal/cpp/cryptography/ecc.hpp>
NIST prime curves: P-256 (ECDH, ECDSA) and P-384 (ECDSA verification).
What TLS 1.3 and X.509 need from the NIST curves. P-256 does key agreement (secp256r1 key share), signs and verifies. P-384 only verifies, since it appears in certificate chains and nothing here signs with it.
ECDSA takes the digest, not the message. The caller hashes (SHA-256 for P-256 in TLS, SHA-384 for P-384), and the digest is truncated to the bit length of the group order as FIPS 186-4 section 6.4 requires.
Signatures exist in two forms. The raw one is r || s, each a big-endian integer of the scalar size. The DER one is the ECDSA-Sig-Value of RFC 3279 (SEQUENCE of two INTEGER), which is what TLS and X.509 carry. Decoding is strict DER.
struct P256
{
/// @brief Scalar (private key, r, s) size, in bytes.staticconstexprstd::size_tSCALAR_SIZE = 32;
/// @brief Uncompressed public key size, in bytes (0x04 || X || Y).staticconstexprstd::size_t PUBLIC_KEY_SIZE = 65;
/// @brief Raw signature size, in bytes (r || s).staticconstexprstd::size_tSIGNATURE_SIZE = 64;
/// @brief Largest DER signature, in bytes.staticconstexprstd::size_t MAX_DER_SIGNATURE_SIZE = 72;
/// @brief The 32 byte private key.using PrivateKey = std::array< std::uint8_t, SCALAR_SIZE >;
/// @brief The 65 byte uncompressed public key.using PublicKey = std::array< std::uint8_t, PUBLIC_KEY_SIZE >;
/// @brief The 32 byte ECDH shared secret (the x coordinate).using SharedSecret = std::array< std::uint8_t, SCALAR_SIZE >;
/// @brief The 64 byte raw signature r || s.using Signature = std::array< std::uint8_t, SIGNATURE_SIZE >;
////// GenerateKeyPair////// @brief Draws a private key in [1, n-1] from the system entropy source and/// computes its public key.////// @param OutPrivate Receives the private key./// @param OutPublic Receives the public key.////// @return false when the entropy source failed. Do not use the outputs.///ETL_API_NOIGNstaticbool GenerateKeyPair( PrivateKey & OutPrivate, PublicKey & OutPublic ) ETL_NOEXCEPT;
////// DerivePublicKey////// @brief Computes the public key d * G.////// @param Private The private key./// @param OutPublic Receives the public key.////// @return false when the private key is not in [1, n-1].///ETL_API_NOIGNstaticbool DerivePublicKey( const PrivateKey & Private, PublicKey & OutPublic ) ETL_NOEXCEPT;
////// IsValidPublicKey////// @brief Checks a SEC1 uncompressed public key.////// @details Exactly 65 bytes, first byte 0x04, both coordinates below p, and/// the point on the curve. The curve has prime order and cofactor 1,/// so a point on it is in the group. The point at infinity has no/// 65 byte encoding.////// @param Public The encoded key.////// @return true when the key is usable.///ETL_API_NOIGNstaticbool IsValidPublicKey( std::span< conststd::uint8_t > Public ) ETL_NOEXCEPT;
////// DeriveShared////// @brief ECDH: the x coordinate of d * Q.////// @details Rejects an invalid peer key (see @ref IsValidPublicKey) and a/// private key out of [1, n-1]. That is the TLS 1.3 secp256r1 key/// share (RFC 8446 section 7.4.2).////// @param Private Our private key./// @param PeerPublic The peer public key, 65 bytes./// @param Out Receives the shared secret. Zeroed on failure.////// @return false on an invalid input.///ETL_API_NOIGNstaticbool DeriveShared( const PrivateKey & Private,
std::span< conststd::uint8_t > PeerPublic,
SharedSecret & Out ) ETL_NOEXCEPT;
////// Sign////// @brief ECDSA signature of a digest, with the RFC 6979 nonce.////// @param Private The private key./// @param Digest The message digest, computed by the caller. Longer than 32/// bytes is truncated to the leftmost 256 bits./// @param Out Receives r || s.////// @return false when the private key is not in [1, n-1] or the digest is/// empty.///ETL_API_NOIGNstaticbool Sign( const PrivateKey & Private, std::span< conststd::uint8_t > Digest,
Signature & Out ) ETL_NOEXCEPT;
////// Verify////// @brief Verifies a raw ECDSA signature over a digest.////// @details Rejects r or s out of [1, n-1], an invalid public key and an/// empty digest. Does not tell the reasons apart.////// @param Public The public key, 65 bytes./// @param Digest The message digest./// @param Sig The raw signature r || s.////// @return true only for a valid signature.///ETL_API_NOIGNstaticbool Verify( std::span< conststd::uint8_t > Public,
std::span< conststd::uint8_t > Digest,
const Signature & Sig ) ETL_NOEXCEPT;
////// VerifyDer////// @brief Verifies a DER encoded ECDSA signature (the TLS and X.509 form).////// @param Public The public key, 65 bytes./// @param Digest The message digest./// @param DerSig The ECDSA-Sig-Value.////// @return true only for a strict DER, valid signature.///ETL_API_NOIGNstaticbool VerifyDer( std::span< conststd::uint8_t > Public,
std::span< conststd::uint8_t > Digest,
std::span< conststd::uint8_t > DerSig ) ETL_NOEXCEPT;
////// SignatureFromDer////// @brief Decodes a DER ECDSA-Sig-Value into r || s.////// @details Strict DER: one SEQUENCE with a short form length that covers the/// input exactly, two INTEGER, minimal encoding (no leading zero/// byte unless the next byte has the top bit set), no negative/// value, and r and s in [1, n-1].////// @param Der The encoding./// @param Out Receives r || s.////// @return false for anything else.///ETL_API_NOIGNstaticbool SignatureFromDer( std::span< conststd::uint8_t > Der, Signature & Out ) ETL_NOEXCEPT;
////// SignatureToDer////// @brief Encodes r || s as a DER ECDSA-Sig-Value.////// @param Sig The raw signature./// @param Out The output buffer. @ref MAX_DER_SIGNATURE_SIZE always fits.////// @return The number of bytes written. 0 when the buffer is too small.///ETL_API_NOIGNstaticstd::size_t SignatureToDer( const Signature & Sig, std::span< std::uint8_t > Out ) ETL_NOEXCEPT;
////// SelfCheckConstants////// @brief Checks the transcribed curve constants.////// @details p must equal 2^256 - 2^224 + 2^192 + 2^96 - 1 (built here from/// the formula), G must be on the curve, and n * G must be the/// point at infinity.////// @return true when every check passes.///ETL_API_NOIGNstaticbool SelfCheckConstants() ETL_NOEXCEPT;
};
The NIST P-256 curve (secp256r1, prime256v1): ECDH and ECDSA.
Public keys are SEC1 uncompressed points: 0x04 || X || Y, 65 bytes. Private keys are 32 byte big-endian scalars in [1, n-1].
Constant time where there is a secret. Key generation, public key derivation, ECDH and signing run the same instructions and touch the same addresses for any private key or nonce: a fixed 4 bit window over the whole scalar, complete addition formulas (Renes, Costello and Batina 2016, no special case for doubling or for the point at infinity), a table lookup that reads all 16 entries and keeps one by mask, and inversion by Fermat (a^(n-2), fixed exponent). Verification handles only public data.
Signing is deterministic (RFC 6979, HMAC-SHA256), so no random generator is involved and a weak one cannot leak the key. With a SHA-256 digest the signature matches the RFC 6979 vectors byte for byte. With a digest of another size the nonce still follows RFC 6979 with HMAC-SHA256 and the signature is valid, but it will not match a signer that uses the digest hash for the HMAC.
struct P384
{
/// @brief Scalar (r, s) size, in bytes.staticconstexprstd::size_tSCALAR_SIZE = 48;
/// @brief Uncompressed public key size, in bytes (0x04 || X || Y).staticconstexprstd::size_t PUBLIC_KEY_SIZE = 97;
/// @brief Raw signature size, in bytes (r || s).staticconstexprstd::size_tSIGNATURE_SIZE = 96;
/// @brief Largest DER signature, in bytes.staticconstexprstd::size_t MAX_DER_SIGNATURE_SIZE = 104;
/// @brief The 97 byte uncompressed public key.using PublicKey = std::array< std::uint8_t, PUBLIC_KEY_SIZE >;
/// @brief The 96 byte raw signature r || s.using Signature = std::array< std::uint8_t, SIGNATURE_SIZE >;
////// IsValidPublicKey////// @brief Checks a SEC1 uncompressed public key (97 bytes, 0x04, both/// coordinates below p, point on the curve).////// @param Public The encoded key.////// @return true when the key is usable.///ETL_API_NOIGNstaticbool IsValidPublicKey( std::span< conststd::uint8_t > Public ) ETL_NOEXCEPT;
////// Verify////// @brief Verifies a raw ECDSA signature over a digest.////// @param Public The public key, 97 bytes./// @param Digest The message digest. Longer than 48 bytes is truncated./// @param Sig The raw signature r || s.////// @return true only for a valid signature.///ETL_API_NOIGNstaticbool Verify( std::span< conststd::uint8_t > Public,
std::span< conststd::uint8_t > Digest,
const Signature & Sig ) ETL_NOEXCEPT;
////// VerifyDer////// @brief Verifies a DER encoded ECDSA signature.////// @param Public The public key, 97 bytes./// @param Digest The message digest./// @param DerSig The ECDSA-Sig-Value.////// @return true only for a strict DER, valid signature.///ETL_API_NOIGNstaticbool VerifyDer( std::span< conststd::uint8_t > Public,
std::span< conststd::uint8_t > Digest,
std::span< conststd::uint8_t > DerSig ) ETL_NOEXCEPT;
////// SignatureFromDer////// @brief Decodes a DER ECDSA-Sig-Value into r || s (same rules as/// @ref P256::SignatureFromDer).////// @param Der The encoding./// @param Out Receives r || s.////// @return false for anything that is not strict DER with r, s in [1, n-1].///ETL_API_NOIGNstaticbool SignatureFromDer( std::span< conststd::uint8_t > Der, Signature & Out ) ETL_NOEXCEPT;
////// SignatureToDer////// @brief Encodes r || s as a DER ECDSA-Sig-Value.////// @param Sig The raw signature./// @param Out The output buffer. @ref MAX_DER_SIGNATURE_SIZE always fits.////// @return The number of bytes written. 0 when the buffer is too small.///ETL_API_NOIGNstaticstd::size_t SignatureToDer( const Signature & Sig, std::span< std::uint8_t > Out ) ETL_NOEXCEPT;
////// SelfCheckConstants////// @brief Checks the transcribed curve constants.////// @details p must equal 2^384 - 2^128 - 2^96 + 2^32 - 1, G must be on the/// curve, and n * G must be the point at infinity.////// @return true when every check passes.///ETL_API_NOIGNstaticbool SelfCheckConstants() ETL_NOEXCEPT;
};
The NIST P-384 curve (secp384r1): ECDSA verification only.
Public keys are SEC1 uncompressed points, 97 bytes. Nothing here signs with P-384 or does ECDH with it.
Not constant time, on purpose: verification touches no secret. The public key, the digest and the signature are all public.
Computes a fast hash with strong dispersion (avalanche), processing the data in 64-bit blocks and then the remaining bytes. The algorithm uses:
Large primes to spread the bits evenly.
Bitwise rotations to mix the high and low bits.
A final avalanche step inspired by MurmurHash, reducing correlation and trivial collisions.
The function is deterministic for the same input + seed (the seed comes from the build and the product license), does not allocate, and fits performance critical paths.
DataPtr
Pointer to the block of data to process.
DataLength
Size of the block in bytes.
64-bit hash of the given data.
hmac.hpp
#include <ethereal/cpp/cryptography/hmac.hpp>
HMAC (RFC 2104) and HKDF (RFC 5869) over SHA-256, SHA-384 and SHA-512.
One shot and incremental HMAC, and HKDF Extract and Expand. Written for TLS 1.3, whose key schedule is HKDF over the hash of the cipher suite (SHA-256 or SHA-384).
The HMAC objects are copyable by value: a copy carries the keyed state, so a tag over a prefix can be taken from a copy while the original keeps absorbing.
The older Ethereal::Crypto::HmacSha256, Ethereal::Crypto::HkdfExtract and Ethereal::Crypto::HkdfExpand in aead.hpp stay as they are. These classes give the same bytes for SHA-256.
template< class TStream, std::size_t uBlock, std::size_t uDigest > classCHmac
Use the aliases CHmacSha256, CHmacSha384 and CHmacSha512. Only those three are instantiated in the library.
The key is absorbed once, in SetKey: the inner and outer padded blocks are compressed and their states kept. Each tag after that costs the message plus two compressions.
After Final the object is back at the keyed initial state, so it can authenticate another message with the same key.
The destructor wipes the keyed states with SecureZero.
TStream
The incremental digest (CSha256Stream, CSha384Stream or CSha512Stream).
uBlock
The block size of the digest, in bytes.
uDigest
The digest size, in bytes.
Not thread safe. Copy it to use the same key in several threads.
template< class THmac >
structCHkdf
{
/// @brief Size of the pseudorandom key and of each expansion block, in bytes.staticconstexprstd::size_t HashSize = THmac::DigestSize;
/// @brief Largest output of @ref Expand: 255 blocks.staticconstexprstd::size_t MaxOutput = 255u * THmac::DigestSize;
////// Extract////// @brief HKDF-Extract: PRK = HMAC( Salt, Ikm ).////// @param Salt The salt. Empty means a string of HashSize zeros (the same HMAC key)./// @param Ikm The input keying material.////// @return The pseudorandom key (PRK).///staticstd::array< std::uint8_t, THmac::DigestSize > Extract( std::span< conststd::uint8_t > Salt,
std::span< conststd::uint8_t > Ikm ) noexcept;
////// Expand////// @brief HKDF-Expand: fills @p Out with T(1) | T(2) | ...////// @param Prk The pseudorandom key. At least HashSize bytes (RFC 5869, 2.3)./// @param Info The context label./// @param Out Where to write. Up to @ref MaxOutput bytes. May be empty.////// @return false when @p Prk is shorter than HashSize or @p Out is larger than/// @ref MaxOutput. @p Out is left untouched in that case.///ETL_API_NOIGNstaticbool Expand( std::span< conststd::uint8_t > Prk,
std::span< conststd::uint8_t > Info,
std::span< std::uint8_t > Out ) noexcept;
};
HKDF over one HMAC.
Use the aliases CHkdfSha256, CHkdfSha384 and CHkdfSha512. Stateless: two static functions.
Intermediate values (the T(i) blocks and the HMAC states) are wiped with SecureZero before returning.
THmac
The HMAC (CHmacSha256, CHmacSha384 or CHmacSha512).
RSA signature verification: PKCS #1 v1.5 and PSS (RFC 8017).
What TLS 1.3 and X.509 need from RSA: checking certificate signatures (mostly PKCS #1 v1.5) and the CertificateVerify of a server with an RSA key (PSS, rsa_pss_rsae_*). Nothing here signs, decrypts or encrypts.
The caller hashes. The verification takes the digest, already computed with the hash the signature names.
An RSA public key (n, e) that verifies signatures.
classCRsaPublicKey
The modulus must have 2048 to 8192 bits. Below 2048 bits RSA is no longer accepted by the CA/Browser Forum nor by NIST (SP 800-131A), and a key that small in a TLS chain is an error to report, not a case to support. Above 8192 bits no public CA issues keys, and the bound keeps the working buffers fixed (no allocation).
The exponent must be odd, at least 3 and below n. 65537 is the usual value.
Not constant time, on purpose. Verification uses only public values (the key, the signature, the digest), so the run time leaks nothing. The exponentiation is Montgomery square and multiply over the bits of e, and it branches on those bits.
Loads (n, e) from big-endian bytes, as in the X.509 RSAPublicKey. Leading zero bytes are allowed (DER puts one in front of n).
Modulus
n, big-endian.
Exponent
e, big-endian.
false when the modulus is out of 2048 to 8192 bits, n is even, or e is even, below 3 or not below n, or when the library is not licensed. The object is then empty.
Builds the whole expected encoding 00 01 FF..FF 00 DigestInfo and compares it with the recovered one. It does not parse the recovered DigestInfo, which is the classic hole (Bleichenbacher 2006 signature forgery with e = 3). The DigestInfo is the DER one with the NULL parameters, the form RFC 8017 prescribes.
RSASSA-PSS verification (RFC 8017 section 8.1.2), MGF1 with the same hash.
TLS 1.3 uses a salt as long as the digest (RFC 8446 section 4.2.3). Pass PSS_SALT_ANY to accept any salt length.
eHash
The hash of the signature, also used by MGF1.
Digest
The digest, exactly the size of that hash.
Signature
The signature, exactly ModulusSize bytes.
uSaltSize
The expected salt length, or PSS_SALT_ANY.
true only for a valid signature.
sha.hpp
#include <ethereal/cpp/cryptography/sha.hpp>
SHA-256, SHA-384 and SHA-512 digests (FIPS 180-4).
One pass digests over a buffer, the two region SHA-512 that Ed25519 needs, and incremental SHA-256, SHA-384 and SHA-512 for data that arrives in pieces.
structSHA256
{
/// @brief Digest size, in bytes.staticconstexprstd::size_t DigestSize = 32;
////// Get////// @brief Computes the SHA-256 of a binary buffer.////// @param Data Input buffer.////// @return 32 byte digest, in network order (big-endian), as the standard defines.///staticstd::array< std::uint8_t, DigestSize > Get( std::span< conststd::uint8_t > Data );
////// Get////// @brief Computes the SHA-256 of a string.////// @details Views the string as bytes without a copy. The null terminator/// is not part of the digest.////// @param Str Input string. A null pointer returns the digest of the empty input.////// @return 32 byte digest.///staticstd::array< std::uint8_t, DigestSize > Get( constchar * Str );
////// GetAs_String////// @brief Computes the SHA-256 and writes it as lowercase hexadecimal.////// @details The text is written straight into the output string. No value/// is returned.////// @param Str Input string./// @param StrOut Receives the digest in hexadecimal (64 characters).///staticvoid GetAs_String( constchar * Str, std::string & StrOut );
};
SHA-256 cryptographic digest, as in FIPS 180-4.
One pass, no state between calls and no allocation. The whole digest is computed over the given buffer and returned by value. For data that arrives in pieces, use CSha256Stream.
SHA-256 is for integrity and content fingerprints. It is not a password derivation function. For passwords use an algorithm with a tunable cost (Argon2, scrypt, bcrypt), never a plain SHA.
structSHA512
{
/// @brief Digest size, in bytes.staticconstexprstd::size_t DigestSize = 64;
/// @brief Compression block size, in bytes.////// @details Exposed because constructions built on SHA-512 (HMAC, for/// example) need the block size, not the digest size, to build/// their masks.///staticconstexprstd::size_t BlockSize = 128;
////// Get////// @brief Computes the SHA-512 of a binary buffer.////// @param Data Input buffer.////// @return 64 byte digest, in network order (big-endian), as the standard defines.///staticstd::array< std::uint8_t, DigestSize > Get( std::span< conststd::uint8_t > Data );
////// Get////// @brief Computes the SHA-512 of a string.////// @details The null terminator is not part of the digest.////// @param Str Input string. A null pointer returns the digest of the empty input.////// @return 64 byte digest.///staticstd::array< std::uint8_t, DigestSize > Get( constchar * Str );
////// Get////// @brief Computes the SHA-512 of two regions in sequence, without joining them.////// @details Ed25519 digests `R || A || M`, where M can be large. Without this/// form the caller would have to allocate a copy just to put 64 bytes/// in front of the message.////// @param First First region. May be empty./// @param Second Second region. May be empty.////// @return 64 byte digest of First followed by Second.///staticstd::array< std::uint8_t, DigestSize > Get( std::span< conststd::uint8_t > First,
std::span< conststd::uint8_t > Second );
////// GetAs_String////// @brief Computes the SHA-512 and writes it as lowercase hexadecimal.////// @param Str Input string./// @param StrOut Receives the digest in hexadecimal (128 characters).///staticvoid GetAs_String( constchar * Str, std::string & StrOut );
};
SHA-512 cryptographic digest, as in FIPS 180-4.
Same shape as SHA256: one pass, no state between calls and no allocation. The word is 64 bits instead of 32, with 80 rounds instead of 64, a 128 byte block instead of 64 and a 64 byte digest instead of 32.
Added because the Ed25519 signature (Ethereal::Crypto::Ed25519) requires SHA-512 by definition (RFC 8032). Like SHA-256, it is for integrity and fingerprints, and for the same reason not for passwords.
On a 64 bit machine SHA-512 is usually faster than SHA-256 on large inputs, since it processes twice the bytes per block.
structSHA384
{
/// @brief Digest size, in bytes.staticconstexprstd::size_t DigestSize = 48;
/// @brief Compression block size, in bytes. The same as SHA-512.staticconstexprstd::size_t BlockSize = 128;
////// Get////// @brief Computes the SHA-384 of a binary buffer.////// @param Data Input buffer.////// @return 48 byte digest, in network order (big-endian).///staticstd::array< std::uint8_t, DigestSize > Get( std::span< conststd::uint8_t > Data );
};
SHA-384 cryptographic digest, as in FIPS 180-4 (2026-10-11).
SHA-512 with another initial state, truncated to 48 bytes. Same compression core as SHA512. Added for TLS 1.3, where the TLS_AES_256_GCM_SHA384 suite and the P-384 signatures use it.
Incremental SHA-256: the bytes arrive in pieces (2026-09-28).
classCSha256Stream
Same digest as SHA256::Get over the concatenated pieces, with the same compression core. Meant for data that does not fit in memory: a download of a multi gigabyte artifact is hashed while it arrives, with 104 bytes of state. No allocation.
After Final the object is back in its initial state and can hash another message without Reset.
Incremental SHA-512: the bytes arrive in pieces (2026-10-11).
classCSha512Stream
Same digest as SHA512::Get over the concatenated pieces, with the same compression core. No allocation.
Copyable by value. A copy carries the whole state, so the digest of a prefix can be taken from a copy while the original keeps absorbing (the TLS transcript hash does this).
After Final the object is back in its initial state.
The other crypto modules here are symmetric: whoever verifies needs the same key as whoever produced. Between two ends that already trust each other (CSecureTransform, for example) that is enough.
For licenses it is not, and that is why this file exists. With a symmetric check, the secret that validates the license has to be inside the library the customer receives. Whoever has the library has the secret, and whoever has the secret can mint licenses. The whole scheme falls to a disassembler and a free afternoon, and it cannot be fixed without reissuing everything.
Ed25519 breaks that symmetry. The private key stays in the generator, which never leaves the issuer's machine. The product ships the public key, which verifies and cannot sign. Whoever disassembles the customer binary finds the public key, and it alone is useless for forging.
What this does not solve: license checks run on the customer machine, and no cryptography stops the customer from skipping the check by patching the binary. What the asymmetric signature prevents is someone becoming a license supplier. Without the private key there is no generator, and the attack changes from "run a keygen" to "patch each customer installation, one by one".
Implemented as in RFC 8032 (pure Ed25519, no context and no prehash).
struct Ed25519
{
/// @brief Seed (private key) size, in bytes.////// @details The RFC calls these 32 bytes the "private key". The signing key/// itself is derived from them by SHA-512 and is never stored.///staticconstexprstd::size_tSEED_SIZE = 32;
/// @brief Public key size, in bytes.staticconstexprstd::size_t PUBLIC_KEY_SIZE = 32;
/// @brief Signature size, in bytes.staticconstexprstd::size_tSIGNATURE_SIZE = 64;
/// @brief The 32 byte seed.using Seed = std::array< std::uint8_t, SEED_SIZE >;
/// @brief The 32 byte public key.using PublicKey = std::array< std::uint8_t, PUBLIC_KEY_SIZE >;
/// @brief The 64 byte signature.using Signature = std::array< std::uint8_t, SIGNATURE_SIZE >;
////// GenerateSeed////// @brief Draws a new seed from the system entropy source.////// @details Use this once, to create the product key pair, and keep the seed/// where it never travels with what is distributed.////// @param Out Receives the 32 bytes of the seed.////// @return true when the system entropy source answered. false means no seed/// was drawn. Do not use the output.///ETL_API_NOIGNstaticbool GenerateSeed( Seed & Out ) ETL_NOEXCEPT;
////// DerivePublicKey////// @brief Derives the public key that matches a seed.////// @param Secret 32 byte seed.////// @return 32 byte public key.///ETL_API_NOIGNstatic PublicKey DerivePublicKey( const Seed & Secret ) ETL_NOEXCEPT;
////// Sign////// @brief Signs a message.////// @param Secret 32 byte seed./// @param Message The message. May be empty.////// @return 64 byte signature.///ETL_API_NOIGNstatic Signature Sign( const Seed & Secret,
std::span< conststd::uint8_t > Message ) ETL_NOEXCEPT;
////// Verify////// @brief Verifies a signature.////// @details Does not throw and does not tell the reasons apart: a malformed/// public key, a non canonical signature and a plainly wrong/// signature all return the same false. A license check should/// not know why it failed. The difference would only help someone/// trying to forge.////// @param Public 32 byte public key./// @param Message The verified message./// @param Sig 64 byte signature.////// @return true only if the signature is from Public over Message.///ETL_API_NOIGNstaticbool Verify( const PublicKey & Public,
std::span< conststd::uint8_t > Message,
const Signature & Sig ) ETL_NOEXCEPT;
////// SelfCheckConstants////// @brief Checks the internal curve constants against their definitions.////// @details Makes the central claim verifiable, like @c RawStorage in the/// obfuscation module. A curve constant typed wrong produces an/// implementation that is internally consistent (it signs and/// verifies itself without complaint) and is still not Ed25519./// Round trip tests do not catch that.////// Checks that d = -121665/121666, that 2d is twice d, and that the/// sqrt(-1) constant squared is really -1 in the field.////// @return true when every constant matches its definition.///ETL_API_NOIGNstaticbool SelfCheckConstants() ETL_NOEXCEPT;
};
Ed25519 digital signature, as in RFC 8032.
Twisted Edwards curve over GF(2^255-19). 64 byte signature, 32 byte public key, 32 byte private key (seed). Deterministic: the same seed and the same message always give the same signature. This is a property of the standard. No random generator is involved in signing, so a weak generator cannot leak the key, which is the classic way ECDSA fails.
Verification here is strict. Besides the group equation, it rejects a signature whose scalar S is not reduced (S >= L) and a point encoding that is not canonical. That removes malleability: given a valid signature, there is no way to produce a second, different one that also passes. For licenses this matters, since a malleable signature would be a distinct serial number for the same license.
On constant time: Sign and DerivePublicKey run in time independent of the key value (the multiplication ladder uses a conditional swap with no branch). Still, the private key exists only on the issuer's machine. The customer product carries only Verify, which touches no secret.
This signs and verifies. It does not do key agreement and must not be reused for it. Ed25519 and X25519 use the same curve but different representations and key domains, and mixing them is a known mistake.
Converts a binary buffer to a lowercase hexadecimal string. Converts a block of binary data straight to its hexadecimal form (base 16), with lowercase characters (0-9, a-f). The conversion runs byte by byte, with no intermediate allocation.
Data
Input binary buffer.
StrHexOut
Output string with the lowercase hexadecimal of the buffer.
Converts a std::string_view to a span of bytes (uint8_t). Reads the internal memory of the string as a binary buffer of constant bytes. Does not copy the data and does not allocate. The returned span is valid only while the original string exists.
template< typename T > std::span< conststd::uint8_t > AsBytes( const T & v )
Converts any object to a span of bytes (uint8_t). Reinterprets the binary representation of an object in memory as a contiguous buffer of constant bytes. Does not copy and does not allocate.
*** Warning: The type T must be 'trivially copyable' to be used safely. The returned span is valid only while the original object exists.
T
Type of the object.
v
Input object.
Constant span over the bytes of the object.
x25519.hpp
#include <ethereal/cpp/cryptography/x25519.hpp>
X25519 key agreement (RFC 7748).
Diffie-Hellman over Curve25519 with the Montgomery ladder. It is the default key exchange of TLS 1.3. The field arithmetic is the one Ed25519 uses (one code, covered by the vectors and the oracle of both).
struct X25519
{
/// @brief Size of every key and of the shared secret, in bytes.staticconstexprstd::size_t KEY_SIZE = 32;
/// @brief The 32 byte private key (scalar, clamped on use).using PrivateKey = std::array< std::uint8_t, KEY_SIZE >;
/// @brief The 32 byte public key (u coordinate, little-endian).using PublicKey = std::array< std::uint8_t, KEY_SIZE >;
/// @brief The 32 byte shared secret.using SharedSecret = std::array< std::uint8_t, KEY_SIZE >;
////// GeneratePrivateKey////// @brief Draws a private key from the system entropy source.////// @param Out Receives the 32 bytes.////// @return false when the entropy source gave all zeros. Do not use the output.///ETL_API_NOIGNstaticbool GeneratePrivateKey( PrivateKey & Out ) ETL_NOEXCEPT;
////// DerivePublicKey////// @brief Computes the public key, X25519(k, 9).////// @param Private The private key.////// @return The 32 byte public key.///ETL_API_NOIGNstatic PublicKey DerivePublicKey( const PrivateKey & Private ) ETL_NOEXCEPT;
////// DeriveShared////// @brief Computes the shared secret with the peer public key.////// @details Rejects an all zero result, as TLS 1.3 requires (RFC 8446/// section 7.4.2). It comes from a peer key of small order, and/// accepting it would let the peer force a known secret. The/// check reads every byte and does not branch until the end.////// @param Private Our private key./// @param Peer The peer public key./// @param Out Receives the shared secret. Zeroed on failure.////// @return false when the result is all zeros.///ETL_API_NOIGNstaticbool DeriveShared( const PrivateKey & Private, const PublicKey & Peer,
SharedSecret & Out ) ETL_NOEXCEPT;
////// ScalarMult////// @brief The raw X25519 function of RFC 7748 section 5.////// @details Clamps the scalar, masks the top bit of u, and returns the/// result with no zero check. For test vectors and for callers/// that apply their own policy. Key agreement should use/// @ref DeriveShared.////// @param Scalar 32 byte scalar./// @param U 32 byte u coordinate.////// @return The 32 byte u coordinate of the result.///ETL_API_NOIGNstaticstd::array< std::uint8_t, KEY_SIZE > ScalarMult(
conststd::array< std::uint8_t, KEY_SIZE > & Scalar,
conststd::array< std::uint8_t, KEY_SIZE > & U ) ETL_NOEXCEPT;
};
X25519 key agreement, as in RFC 7748.
32 byte private key, 32 byte public key (the u coordinate), 32 byte shared secret. The scalar is clamped as the RFC requires, and the top bit of a received u is ignored.
Constant time: the ladder takes 255 steps for any scalar and swaps the working points with a mask, never with a branch.
The shared secret is raw. Feed it to a key derivation (HKDF in TLS 1.3), never use it as a key directly.
The state is atomic and each step is taken with a compare and swap, so every step goes to one call only. The old plain static was a data race: two threads could read the same state and get the same key. With one thread the sequence is the same as before.
template< ETL_INT32 N >
structETL_CT_Random
{
staticconstexpruint32_t a = 16807;
staticconstexpruint32_t m = 2147483647;
staticconstexpruint32_t s = ETL_CT_Random<N - 1>::value;
staticconstexpruint32_t lo = a * (s & 0xFFFF);
staticconstexpruint32_t hi = a * (s >> 16);
staticconstexpruint32_t lo2 = lo + ((hi & 0x7FFF) << 16);
staticconstexpruint32_t lo3 = lo2 + (hi >> 15);
staticconstexpruint32_t value = (lo3 > m) ? lo3 - m : lo3;
};
Decrypts into another buffer. The stored bytes are not touched.
Replaces the old 'decrypt()', which had two serious defects. It decrypted in place and never encrypted again, so after the first use the text stayed in clear in memory for good. And it returned a pointer into the object, which the macro created as a temporary, so the pointer was dangling from the start.
Being const, this version can also be called on a 'constexpr' object. That keeps the encrypted bytes in the data section and the clear text out of the binary.
Decrypts on construction and wipes on destruction.
template< std::size_t N, typename Char > classETL_XorScoped
This fixes the dangling pointer. The clear text lives here, and this object lives until the end of the expression that created it. That is enough for a function call, and not enough to keep the pointer.
Do not keep the pointer. When it must survive, as in a function that returns 'const char*', use ETL_XORSTR_STATIC, which decrypts once into a permanent place.
Run time obfuscation of bytes, text, values and pointers.
This is obfuscation, not cryptography. The key lives in the same process as the data. Whoever can stop the program in a debugger reads both, and no byte arrangement trick changes that.
What it buys:
'strings' on the binary no longer shows the text, so the cheapest reverse engineering path (opening the executable in an editor and reading the messages) stops working.
A memory scan for a known pattern does not find the text, because it is not in clear while stored.
Two copies of the same text do not look alike in memory (each object has its own salt), so searching for repeated blocks does not help either.
The cost for someone just snooping goes from minutes to hours.
What it does not buy:
Anything against someone with a debugger and patience.
Real confidentiality. For that there is Ethereal::Crypto, with a key that does not live in the process. If the secret matters, it does not belong here.
Compile time and run time are different cases. ETL_XORSTR in xor.hpp encrypts at compile time and only works for literals. It protects the binary on disk. This file covers text that only exists at run time: a license key read from a file, a token received from the network, a path built on the fly. No literal protects that, because there was no literal.
The five rules:
1. The key is not stored next to the data. This was the classic mistake of the previous version of this code: a 'key_' member next to a 'storage_' member. In a memory dump both come out together, and undoing the XOR is one line of script. Here the key does not exist anywhere while the object is idle. It is derived on each use from three things: the process key (drawn once), the object salt and the object address. A memory dump has the salt and the cipher text, and neither is enough.
2. Because of that, the object cannot be relocated with 'memcpy'. The key depends on the address. Copying the bytes of the object elsewhere without the constructor produces garbage on reveal. Copy and move are implemented and redo the math. Treating this as a trivially copyable type does not work.
3. Revealing is scoped, and the object stays encrypted. CXorString::Reveal returns an object that holds the clear text in its own buffer and wipes it when it goes out of scope. The stored data is never in clear, unlike the previous version, whose 'decrypt()' decrypted in place and left it so for good.
4. The length is not hidden. It stays visible, and sometimes it already gives away what was meant to be hidden (a 32 byte field next to a 6 byte one). CXorString::Assign takes a minimum padding for that case.
5. Compare without revealing. CXorString::Equals compares without returning the text to the caller and without leaving the value in clear longer than needed. The comparison is constant time over the common length.
Comes from Ethereal::Random::SecureBytes on the first call. Two runs of the same program obfuscate the same text differently, which prevents comparing memory dumps across runs.
With the key at zero the XOR is the identity and the value stays in clear in memory, which is what the module exists to avoid. Every round trip test passed, because a round trip with a zero key works perfectly. The check that searches for the value bytes inside the object is what caught it.
Public because whoever writes their own container needs it, and because hiding the formula would protect nothing: it is written here and in the source. What protects is that the process key is not predictable.
The buffer belongs to this object. The source stays obfuscated the whole time. When it goes out of scope, the clear text is wiped with Ethereal::Crypto::SecureZero.
Do not keep the pointer. It dies with the reveal. That is the difference from the previous design, which decrypted in place and left the text in clear for good.
Makes the central claim of this module verifiable: a test can check that the clear text is not here. An obfuscation library that does not allow measuring whether it obfuscates asks for trust instead of proof.
It weakens nothing. Whoever has the process already has these bytes. What does not come out of here is the key, which is not even stored.
Ethereal::Xor::CXorString Token( sFromNetwork );
/// ... the token stays obfuscated while stored ...
{
constauto Plain = Token.Reveal();
Use( Plain.Text() ); /// narrow window, on purpose
}
/// here the clear text is already wiped
Minimum padding, in bytes. The stored content is at least this size, filled with random bytes, and Size is still the real size. This serves rule 4: a fixed size field does not give away what is inside.
Makes the central claim of this module verifiable: a test can check that the clear text is not here. An obfuscation library that does not allow measuring whether it obfuscates asks for trust instead of proof.
It weakens nothing. Whoever has the process already has these bytes. What does not come out of here is the key, which is not even stored.
A copy in clear, which becomes the caller's problem.
From here on there is a std::string in clear in memory, and nobody wipes it. It exists because it is sometimes really needed, and it is marked so that it is a choice and not an oversight. Prefer Reveal.
Digests (SHA-256, SHA-384, SHA-512), HMAC, HKDF, authenticated encryption (AES-GCM and ChaCha20-Poly1305), Ed25519, X25519, the system cryptographic generator, constant time comparison, secure wipe, CRC-32 and CRC-64. The semantics are the ones of the C++ side in 'ethereal/cpp/cryptography/'.
Every export returns 'int'. Zero is success, negative is an error. The values are part of the ABI: never reordered, never reused, only appended at the end.
Output of variable size goes to a buffer with its capacity and the number of bytes written. When it does not fit, the call returns ETLC_ERR_BUFFER_TOO_SMALL and writes the size it needs, so 'uCap = 0' asks for the size. Keys and signatures of fixed size are small structs, and their size is the type.
A null input pointer is accepted only with a zero length.
What does not cross: P-256, P-384 and RSA (used by TLS, and their C++ types carry key state that would need handles of their own), raw AES blocks, raw ChaCha20 and Poly1305, the string obfuscation of 'xor.hpp' (templates resolved at compile time), and 'Hash::Hash64', whose value depends on a seed of the build and so cannot be stored.
Encrypts and authenticates. The output is the cipher text followed by the tag, uIn + ETLC_CRYPTO_AEAD_TAG_SIZE bytes.
Never reuse a nonce with the same key: with either algorithm that reveals the XOR of the two texts and allows forgery. pOut may be the same buffer as pIn.
uAlgorithm
One of the ETLC_CRYPTO_AEAD_* values.
pKey
The key.
uKey
Key size: 16, 24 or 32 for AES-GCM, 32 for ChaCha20-Poly1305.
pNonce
The nonce, ETLC_CRYPTO_AEAD_NONCE_SIZE bytes.
uNonce
Nonce size, in bytes.
pAad
Associated data, authenticated and not encrypted. May be null when uAad is zero.
uAad
Size of the associated data.
pIn
The plain text. May be null when uIn is zero.
uIn
Size of the plain text.
pOut
Receives the cipher text and the tag.
uCap
Capacity of pOut.
pWritten
Receives the output size. Cannot be null.
ETLC_CRYPTO_OK, or one of the ETLC_CRYPTO_ERR_* codes. Also ETLC_ERR_NOT_LICENSED when the library is not licensed.
Checks the tag and decrypts. The input is the cipher text followed by the tag. The output has uIn - ETLC_CRYPTO_AEAD_TAG_SIZE bytes.
The tag is checked before any plain text is released. When it does not match, the call returns ETLC_ERR_VERIFY_FAILED, writes zero in *pWritten and leaves zeros in the output.
uAlgorithm
One of the ETLC_CRYPTO_AEAD_* values.
pKey
The key.
uKey
Key size, as in ETLC_CryptoAeadEncrypt.
pNonce
The nonce used to encrypt.
uNonce
Nonce size, in bytes.
pAad
The same associated data. May be null when uAad is zero.
uAad
Size of the associated data.
pIn
Cipher text followed by the tag.
uIn
Input size. At least ETLC_CRYPTO_AEAD_TAG_SIZE.
pOut
Receives the plain text. May be the same buffer as pIn.
uCap
Capacity of pOut.
pWritten
Receives the plain text size. Cannot be null.
ETLC_CRYPTO_OK, or one of the ETLC_CRYPTO_ERR_* codes. Also ETLC_ERR_NOT_LICENSED when the library is not licensed.