Source
stdlib/hashlib/hashlib.cpp
1
// Copyright (c) 2026 BigBrain LLC. MIT-licensed (see LICENSE).2
// Original work; see ACKNOWLEDGMENTS.md for the open-source ideas we build upon.3
#include "hashlib.hpp"5
#include <array>6
#include <cstdint>7
#include <stdexcept>8
#include <vector>10
namespace cheatah::hashlib {12
namespace {14
inline std::uint32_t rotr(std::uint32_t x, std::uint32_t n) {15
return (x >> n) | (x << (32 - n));16
}18
constexpr std::uint32_t K[64] = {19
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,20
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,21
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,22
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,23
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,24
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,25
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,26
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,27
};29
inline std::uint64_t rotr64(std::uint64_t x, unsigned n) {30
return (x >> n) | (x << (64 - n));31
}33
// SHA-512 round constants (first 64 bits of the fractional parts of the cube roots of34
// the first 80 primes) and initial hash values (square roots of the first 8 primes).35
constexpr std::uint64_t K512[80] = {36
0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,37
0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,38
0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,39
0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,40
0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,41
0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,42
0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,43
0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,44
0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,45
0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,46
0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,47
0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,48
0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,49
0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,50
0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,51
0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,52
0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,53
0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL,54
0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,55
0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL,56
};58
// to_hex / from_hex are this module's PUBLIC canonical byte<->hex helpers (defined after this59
// anonymous namespace, declared in hashlib.hpp). The digest paths below and the tls / ed25519 /60
// x509 modules all share that one implementation instead of re-rolling their own.62
// SHA-256 core: returns the raw 32-byte digest.63
std::array<std::uint8_t, 32> sha256_raw(std::string_view data) {64
std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,65
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};67
// Pad: append 0x80, then zeros, then the 64-bit big-endian bit length.68
const std::uint64_t bitlen = static_cast<std::uint64_t>(data.size()) * 8;69
std::vector<std::uint8_t> msg(data.begin(), data.end());70
msg.push_back(0x80);71
while (msg.size() % 64 != 56) msg.push_back(0x00);72
for (int i = 7; i >= 0; --i) msg.push_back(static_cast<std::uint8_t>(bitlen >> (i * 8)));74
for (std::size_t off = 0; off < msg.size(); off += 64) {75
std::uint32_t w[64];76
for (int i = 0; i < 16; ++i) {77
w[i] = (static_cast<std::uint32_t>(msg[off + i * 4]) << 24) |78
(static_cast<std::uint32_t>(msg[off + i * 4 + 1]) << 16) |79
(static_cast<std::uint32_t>(msg[off + i * 4 + 2]) << 8) |80
(static_cast<std::uint32_t>(msg[off + i * 4 + 3]));81
}82
for (int i = 16; i < 64; ++i) {83
const std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);84
const std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);85
w[i] = w[i - 16] + s0 + w[i - 7] + s1;86
}88
std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3];89
std::uint32_t e = h[4], f = h[5], g = h[6], hh = h[7];90
for (int i = 0; i < 64; ++i) {91
const std::uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);92
const std::uint32_t ch = (e & f) ^ (~e & g);93
const std::uint32_t t1 = hh + S1 + ch + K[i] + w[i];94
const std::uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);95
const std::uint32_t maj = (a & b) ^ (a & c) ^ (b & c);96
const std::uint32_t t2 = S0 + maj;97
hh = g; g = f; f = e; e = d + t1;98
d = c; c = b; b = a; a = t1 + t2;99
}100
h[0] += a; h[1] += b; h[2] += c; h[3] += d;101
h[4] += e; h[5] += f; h[6] += g; h[7] += hh;102
}104
std::array<std::uint8_t, 32> out{};105
for (int i = 0; i < 8; ++i)106
for (int j = 0; j < 4; ++j) out[i * 4 + j] = static_cast<std::uint8_t>(h[i] >> ((3 - j) * 8));107
return out;108
}110
// SHA-512-family core (FIPS 180-4): the 80-round compression over 128-byte blocks, started111
// from the caller's initial hash values. SHA-512 and SHA-384 share everything but the IV and112
// how much of the final state is kept, so both run through this one engine.113
std::array<std::uint8_t, 64> sha512_core(std::string_view data, const std::uint64_t iv[8]) {114
std::uint64_t h[8];115
for (int i = 0; i < 8; ++i) h[i] = iv[i];117
// Pad: 0x80, zeros to a 128-byte block leaving 16 bytes, then the 128-bit big-endian118
// bit length (the high 64 bits are always 0 for our inputs).119
const std::uint64_t bitlen = static_cast<std::uint64_t>(data.size()) * 8;120
std::vector<std::uint8_t> msg(data.begin(), data.end());121
msg.push_back(0x80);122
while (msg.size() % 128 != 112) msg.push_back(0x00);123
for (int i = 0; i < 8; ++i) msg.push_back(0x00); // high 64 bits of the length124
for (int i = 7; i >= 0; --i) msg.push_back(static_cast<std::uint8_t>(bitlen >> (i * 8)));126
for (std::size_t off = 0; off < msg.size(); off += 128) {127
std::uint64_t w[80];128
for (int i = 0; i < 16; ++i) {129
w[i] = 0;130
for (int j = 0; j < 8; ++j)131
w[i] = (w[i] << 8) | msg[off + i * 8 + j];132
}133
for (int i = 16; i < 80; ++i) {134
const std::uint64_t s0 = rotr64(w[i - 15], 1) ^ rotr64(w[i - 15], 8) ^ (w[i - 15] >> 7);135
const std::uint64_t s1 = rotr64(w[i - 2], 19) ^ rotr64(w[i - 2], 61) ^ (w[i - 2] >> 6);136
w[i] = w[i - 16] + s0 + w[i - 7] + s1;137
}139
std::uint64_t a = h[0], b = h[1], c = h[2], d = h[3];140
std::uint64_t e = h[4], f = h[5], g = h[6], hh = h[7];141
for (int i = 0; i < 80; ++i) {142
const std::uint64_t S1 = rotr64(e, 14) ^ rotr64(e, 18) ^ rotr64(e, 41);143
const std::uint64_t ch = (e & f) ^ (~e & g);144
const std::uint64_t t1 = hh + S1 + ch + K512[i] + w[i];145
const std::uint64_t S0 = rotr64(a, 28) ^ rotr64(a, 34) ^ rotr64(a, 39);146
const std::uint64_t maj = (a & b) ^ (a & c) ^ (b & c);147
const std::uint64_t t2 = S0 + maj;148
hh = g; g = f; f = e; e = d + t1;149
d = c; c = b; b = a; a = t1 + t2;150
}151
h[0] += a; h[1] += b; h[2] += c; h[3] += d;152
h[4] += e; h[5] += f; h[6] += g; h[7] += hh;153
}155
std::array<std::uint8_t, 64> out{};156
for (int i = 0; i < 8; ++i)157
for (int j = 0; j < 8; ++j) out[i * 8 + j] = static_cast<std::uint8_t>(h[i] >> ((7 - j) * 8));158
return out;159
}161
// SHA-512: the core with its own initial hash values (square roots of the first 8 primes).162
std::array<std::uint8_t, 64> sha512_raw(std::string_view data) {163
static constexpr std::uint64_t kIv[8] = {164
0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,165
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL};166
return sha512_core(data, kIv);167
}169
// SHA-384: the same core with the SHA-384 initial hash values (square roots of the 9th..16th170
// primes), keeping the leftmost 48 bytes of the final state.171
std::array<std::uint8_t, 48> sha384_raw(std::string_view data) {172
static constexpr std::uint64_t kIv[8] = {173
0xcbbb9d5dc1059ed8ULL, 0x629a292a367cd507ULL, 0x9159015a3070dd17ULL, 0x152fecd8f70e5939ULL,174
0x67332667ffc00b31ULL, 0x8eb44a8768581511ULL, 0xdb0c2e0d64f98fa7ULL, 0x47b5481dbefa4fa4ULL};175
const std::array<std::uint8_t, 64> full = sha512_core(data, kIv);176
std::array<std::uint8_t, 48> out{};177
for (int i = 0; i < 48; ++i) out[i] = full[i];178
return out;179
}181
} // namespace183
std::string sha256(std::string_view data) {184
const auto d = sha256_raw(data);185
return to_hex(d.data(), d.size());186
}188
std::string sha384(std::string_view data) {189
const auto d = sha384_raw(data);190
return to_hex(d.data(), d.size());191
}193
std::string sha512(std::string_view data) {194
const auto d = sha512_raw(data);195
return to_hex(d.data(), d.size());196
}198
std::string sha256_digest(std::string_view data) {199
const auto d = sha256_raw(data);200
return std::string(reinterpret_cast<const char*>(d.data()), d.size());201
}203
std::string sha384_digest(std::string_view data) {204
const auto d = sha384_raw(data);205
return std::string(reinterpret_cast<const char*>(d.data()), d.size());206
}208
std::string sha512_digest(std::string_view data) {209
const auto d = sha512_raw(data);210
return std::string(reinterpret_cast<const char*>(d.data()), d.size());211
}213
// ---- HMAC + HKDF (RFC 2104 / RFC 5869) over the SHA-256 above ----------------------215
std::string hmac_sha256(std::string_view key, std::string_view data) {216
constexpr std::size_t kBlock = 64; // SHA-256 block size217
std::string k(key);218
if (k.size() > kBlock) k = sha256_digest(k); // long keys hash down first219
k.resize(kBlock, '\0');220
std::string inner(kBlock, '\0');221
std::string outer(kBlock, '\0');222
for (std::size_t i = 0; i < kBlock; ++i) {223
inner[i] = static_cast<char>(k[i] ^ 0x36);224
outer[i] = static_cast<char>(k[i] ^ 0x5c);225
}226
return sha256_digest(outer + sha256_digest(inner + std::string(data)));227
}229
std::string hmac_sha384(std::string_view key, std::string_view data) {230
constexpr std::size_t kBlock = 128; // SHA-384 shares SHA-512's 128-byte block231
std::string k(key);232
if (k.size() > kBlock) k = sha384_digest(k); // long keys hash down first233
k.resize(kBlock, '\0');234
std::string inner(kBlock, '\0');235
std::string outer(kBlock, '\0');236
for (std::size_t i = 0; i < kBlock; ++i) {237
inner[i] = static_cast<char>(k[i] ^ 0x36);238
outer[i] = static_cast<char>(k[i] ^ 0x5c);239
}240
return sha384_digest(outer + sha384_digest(inner + std::string(data)));241
}243
std::string hmac_sha512(std::string_view key, std::string_view data) {244
constexpr std::size_t kBlock = 128; // SHA-512 block size245
std::string k(key);246
if (k.size() > kBlock) k = sha512_digest(k); // long keys hash down first247
k.resize(kBlock, '\0');248
std::string inner(kBlock, '\0');249
std::string outer(kBlock, '\0');250
for (std::size_t i = 0; i < kBlock; ++i) {251
inner[i] = static_cast<char>(k[i] ^ 0x36);252
outer[i] = static_cast<char>(k[i] ^ 0x5c);253
}254
return sha512_digest(outer + sha512_digest(inner + std::string(data)));255
}257
// ---- Hex (the one canonical byte<->hex for the whole crypto stack) -----------------259
std::string to_hex(const std::uint8_t* data, std::size_t n) {260
static const char hexd[] = "0123456789abcdef";261
std::string out;262
out.reserve(n * 2);263
for (std::size_t i = 0; i < n; ++i) {264
out.push_back(hexd[data[i] >> 4]);265
out.push_back(hexd[data[i] & 0xF]);266
}267
return out;268
}270
std::string to_hex(std::string_view bytes) {271
return to_hex(reinterpret_cast<const std::uint8_t*>(bytes.data()), bytes.size());272
}274
std::string from_hex(std::string_view hex) {275
if (hex.size() % 2 != 0) throw std::invalid_argument("hashlib::from_hex: odd-length hex");276
auto nibble = [](char c) -> int {277
if (c >= '0' && c <= '9') return c - '0';278
if (c >= 'a' && c <= 'f') return c - 'a' + 10;279
if (c >= 'A' && c <= 'F') return c - 'A' + 10;280
return -1;281
};282
std::string out;283
out.reserve(hex.size() / 2);284
for (std::size_t i = 0; i < hex.size(); i += 2) {285
const int hi = nibble(hex[i]), lo = nibble(hex[i + 1]);286
if (hi < 0 || lo < 0) throw std::invalid_argument("hashlib::from_hex: non-hex character");287
out.push_back(static_cast<char>((hi << 4) | lo));288
}289
return out;290
}292
// ---- Base64 (RFC 4648, standard alphabet) -----------------------------------------294
namespace {295
constexpr char kB64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";296
} // namespace298
std::string base64_encode(std::string_view data) {299
const auto* p = reinterpret_cast<const unsigned char*>(data.data());300
const std::size_t n = data.size();301
std::string out;302
out.reserve(((n + 2) / 3) * 4);303
std::size_t i = 0;304
for (; i + 3 <= n; i += 3) {305
const unsigned v = (static_cast<unsigned>(p[i]) << 16) |306
(static_cast<unsigned>(p[i + 1]) << 8) | static_cast<unsigned>(p[i + 2]);307
out.push_back(kB64[(v >> 18) & 63]);308
out.push_back(kB64[(v >> 12) & 63]);309
out.push_back(kB64[(v >> 6) & 63]);310
out.push_back(kB64[v & 63]);311
}312
if (n - i == 1) {313
const unsigned v = static_cast<unsigned>(p[i]) << 16;314
out.push_back(kB64[(v >> 18) & 63]);315
out.push_back(kB64[(v >> 12) & 63]);316
out.push_back('=');317
out.push_back('=');318
} else if (n - i == 2) {319
const unsigned v =320
(static_cast<unsigned>(p[i]) << 16) | (static_cast<unsigned>(p[i + 1]) << 8);321
out.push_back(kB64[(v >> 18) & 63]);322
out.push_back(kB64[(v >> 12) & 63]);323
out.push_back(kB64[(v >> 6) & 63]);324
out.push_back('=');325
}326
return out;327
}329
std::string base64_decode(std::string_view text, bool strict) {330
std::array<int, 256> rev;331
rev.fill(-1);332
for (int i = 0; i < 64; ++i) rev[static_cast<unsigned char>(kB64[i])] = i;333
std::string out;334
out.reserve((text.size() / 4) * 3);335
int buf = 0;336
int bits = 0;337
for (unsigned char c : text) {338
if (c == '=') break; // padding -> end of data339
const int d = rev[c];340
if (d < 0) {341
// Whitespace is always skipped. Any OTHER non-alphabet byte is silently ignored in the342
// default (lenient) mode, but REJECTED — empty result — in strict mode. X.509 PEM parsing343
// uses strict so a malformed body fails closed instead of decoding to garbage.344
if (strict && c != ' ' && c != '\n' && c != '\r' && c != '\t') return std::string();345
continue; // skip whitespace / (lenient) non-alphabet bytes346
}347
buf = (buf << 6) | d;348
bits += 6;349
if (bits >= 8) {350
bits -= 8;351
out.push_back(static_cast<char>((buf >> bits) & 0xff));352
}353
}354
return out;355
}357
// HKDF (RFC 5869) generic over its HMAC and hash-output length, so the SHA-256 and SHA-384 key358
// schedules (the latter for the TLS_AES_256_GCM_SHA384 cipher suite) share one implementation.359
namespace {360
using HmacFn = std::string (*)(std::string_view, std::string_view);362
std::string hkdf_expand_impl(std::string_view prk, std::string_view info, long long length,363
HmacFn hmac, std::size_t hlen) {364
if (length <= 0 || length > 255 * static_cast<long long>(hlen)) return "";365
std::string okm;366
std::string t; // T(0) = empty367
for (unsigned char counter = 1; static_cast<long long>(okm.size()) < length; ++counter) {368
t = hmac(prk, t + std::string(info) + static_cast<char>(counter));369
okm += t;370
}371
okm.resize(static_cast<std::size_t>(length));372
return okm;373
}374
} // namespace376
std::string hkdf_extract(std::string_view salt, std::string_view ikm) {377
return hmac_sha256(salt, ikm);378
}380
std::string hkdf_expand(std::string_view prk, std::string_view info, long long length) {381
return hkdf_expand_impl(prk, info, length, hmac_sha256, 32);382
}384
std::string hkdf_extract_sha384(std::string_view salt, std::string_view ikm) {385
return hmac_sha384(salt, ikm);386
}388
std::string hkdf_expand_sha384(std::string_view prk, std::string_view info, long long length) {389
return hkdf_expand_impl(prk, info, length, hmac_sha384, 48);390
}392
} // namespace cheatah::hashlib