Cairn
algorithms · cryptography · O(n) time, one pass over the input, 12 rounds of 64-bit mixing per 128-byte block; O(1) space beyond it; output length is a parameter from 1 to 64 bytes, not a fixed width, and keying is built directly into the first block rather than bolted on with a separate nesting construction

↩ back to Cryptography

BLAKE2b

This site's ninth Cryptography entry, bcrypt, named Argon2 — alongside SHA-256's, HMAC's, and PBKDF2's own pages — as the one remaining memory-hard password hash still unbuilt here. Argon2 itself is still unbuilt after this session too, but one real piece of it no longer is: BLAKE2b, the hash function Argon2 uses internally for every one of its own mixing and finalization steps, the same way PBKDF2 leans on this site's own HMAC-SHA256 rather than reinventing a hash. BLAKE2b is also a genuinely different hash construction in its own right, not just plumbing: it operates on 64-bit words instead of SHA-256's 32-bit ones, reuses its 16 message words directly through a fixed permutation schedule each round instead of expanding them into 64 derived words, and — the one property this page spends the most time on — carries a one-bit finalization flag that makes its very last compression step structurally different from every block before it. That single bit is exactly what SHA-256's own Merkle–Damgård construction lacks, and exactly what the length-extension forgery on that page exploits. This page builds BLAKE2b from scratch, verifies it against Python's own standard-library hashlib.blake2b — no extra install needed, unlike bcrypt's or Argon2's own reference libraries — and runs the identical forgery attempt that broke SHA-256 against it live, to watch the finalization flag stop it cold.

Try it

Type a message, an optional key, and pick an output length — the hash updates on every keystroke, computed entirely by this page's own hand-written implementation (see Reference implementation). There's no browser-native crypto.subtle algorithm for BLAKE2b to cross-check against the way SHA-256's page does — the verification for this one happened before it ever reached this page, against Python's trusted library (see below).

The same message and key, hashed at all three lengths above, side by side — none is a truncation of another, unlike SHA-512/256's relationship to SHA-512:

Click to flip the lowest bit of the message's last byte and see how many output bits change at the currently selected length.

BLAKE2b's keyed mode is a complete, built-in MAC — no nesting construction required the way HMAC wraps SHA-256. The demo above already is a keyed hash whenever the key field isn't empty; changing either the key or the message changes the output completely, which is exactly the tamper-detection property a MAC needs. The demo below instead replays SHA-256's own length-extension attack, adapted to this page's unkeyed hash, to check whether the same forgery technique works here too.

Server-side setup, the same naive token = BLAKE2b(secret‖message) scheme SHA-256's own demo used for SHA-256 instead — a 32-byte secret (hidden) is prepended to a request string, then hashed with BLAKE2b at its default 64-byte output.

Attacker's view — knows only the published token above, the request string, and the secret's byte length. Tries the exact same technique that forged a valid token on SHA-256's own page: treat the published token as a resumable internal state, and continue compressing with the extra data appended.

Why it works

BLAKE2b's compression function keeps 16 running 64-bit words, split into a working vector v[0..15]: the first 8 seeded from the running hash state h[0..7], the last 8 from a fixed initialization vector (the same constants SHA-512 uses, borrowed rather than invented). Two of those last 8 words are XORed with a 128-bit byte counter before mixing starts, and — the detail this whole page is really about — one more, v[14], gets bitwise-inverted first, but only on the very last block. Twelve rounds of a mixing function G follow, each round applying G eight times across different quadruples of v, using two of the block's 16 message words each time — picked by a fixed permutation table (SIGMA) that's different every round, not derived by any formula the way SHA-256's 64-word schedule expansion is. G itself is pure ARX — add, rotate, XOR, nothing else — using rotation amounts 32, 24, 16, and 63 bits instead of SHA-256's 32-bit-word rotations. After all 12 rounds, the new hash state is h[i] = h[i] XOR v[i] XOR v[i+8] for each of the 8 words — folding both halves of the mixed vector back together.

Keying and variable output length don't need a separate construction at all: before the first byte of real input is even processed, h[0] is XORed once with 0x01010000 ⊕ (key_length << 8) ⊕ output_length, and if a key is present it's zero-padded to a full 128-byte block and compressed first, as if it were the message's own first block. Both the key's length and the desired output length are baked into the very first compression this way — HMAC needs ipad/opad and two nested hash calls to get a secure keyed construction out of a hash that has no native concept of a key at all; BLAKE2b has one built in from its very first block.

The finalization flag is what defeats length extension. SHA-256's compression function treats every block identically, final or not — the digest is just the running state after the last one, so resuming from a published digest and feeding it more (correctly padded) blocks produces a provably correct hash of the original input with those blocks appended. BLAKE2b's last block is compressed through a different function — same G, same rounds, but with v[14] inverted first — so the published digest is the result of a step that never happens anywhere except at the true end. There is no way to "undo" that inversion and recover what the state would have been had the input kept going, because compress mixes every input word into every output word by design; nothing about it is reversible. Resuming from a final-block digest and compressing more data applies a non-final compression on top of a state that only exists as a final one — a well-defined computation, just not the hash of anything a real input would ever produce. The forgery demo above runs exactly this attempt and checks the result against the true value directly, the same way SHA-256's own demo reveals its ground truth only for comparison, never to the attack itself.

Reference implementation

64-bit words are plain JavaScript BigInt, masked to 64 bits after every operation since BigInt itself is arbitrary-precision. SIGMA is 12 rows of a fixed permutation of 0–15 (row 10 repeats row 0, row 11 repeats row 1 — the schedule only has 10 genuinely distinct rows for 12 rounds):

const MASK64 = (1n << 64n) - 1n;
const IV = [ // borrowed from SHA-512's own initial state, not invented for BLAKE2b
  0x6a09e667f3bcc908n, 0xbb67ae8584caa73bn, 0x3c6ef372fe94f82bn, 0xa54ff53a5f1d36f1n,
  0x510e527fade682d1n, 0x9b05688c2b3e6c1fn, 0x1f83d9abfb41bd6bn, 0x5be0cd19137e2179n
];
const SIGMA = [
  [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], [14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],
  /* … 8 more fixed rows … */              [14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3]
];

function rotr64(x, n) { return ((x >> BigInt(n)) | (x << BigInt(64 - n))) & MASK64; }

function g(v, a, b, c, d, x, y) {
  v[a] = (v[a] + v[b] + x) & MASK64;  v[d] = rotr64(v[d] ^ v[a], 32);
  v[c] = (v[c] + v[d]) & MASK64;      v[b] = rotr64(v[b] ^ v[c], 24);
  v[a] = (v[a] + v[b] + y) & MASK64;  v[d] = rotr64(v[d] ^ v[a], 16);
  v[c] = (v[c] + v[d]) & MASK64;      v[b] = rotr64(v[b] ^ v[c], 63);
}

function compress(h, block /* 128 bytes */, t /* BigInt byte counter */, isLast) {
  const m = readSixteenLEWords(block);
  const v = h.slice().concat(IV);
  v[12] ^= t & MASK64;
  v[13] ^= (t >> 64n) & MASK64;
  if (isLast) v[14] ^= MASK64;          // the one bit that blocks length extension
  for (let r = 0; r < 12; r++) {
    const s = SIGMA[r];
    g(v,0,4,8,12,m[s[0]],m[s[1]]);  g(v,1,5,9,13,m[s[2]],m[s[3]]);
    g(v,2,6,10,14,m[s[4]],m[s[5]]); g(v,3,7,11,15,m[s[6]],m[s[7]]);
    g(v,0,5,10,15,m[s[8]],m[s[9]]); g(v,1,6,11,12,m[s[10]],m[s[11]]);
    g(v,2,7,8,13,m[s[12]],m[s[13]]); g(v,3,4,9,14,m[s[14]],m[s[15]]);
  }
  for (let i = 0; i < 8; i++) h[i] ^= v[i] ^ v[i + 8];
}

function blake2b(messageBytes, outLen, keyBytes) {
  const h = IV.slice();
  h[0] ^= 0x01010000n ^ (BigInt(keyBytes.length) << 8n) ^ BigInt(outLen);
  const input = keyBytes.length
    ? concat(zeroPadTo128(keyBytes), messageBytes)   // key becomes the message's own first block
    : messageBytes;
  // … chunk `input` into 128-byte blocks, compress() each, last one with isLast=true …
  return serializeLE(h).subarray(0, outLen);
}

Verified against Python's own standard-library hashlib.blake2b — no extra package to install, unlike bcrypt's verification against the separate bcrypt library — across the empty message, "abc", a message exactly at the 127/128/129-byte block boundary, a 256-byte multi-block message, keyed hashes at several output lengths, and an empty message with a 1-byte key: all 10 matched exactly before any of this reached the page above. Beyond those fixed cases, 3,000 randomized trials (message lengths 0–400 bytes, output lengths 1–64 bytes, keys present on roughly a third of trials at random lengths up to the 64-byte maximum) matched Python's digest byte-for-byte in every single case, 0 mismatches. The length-extension forgery attempt itself was checked separately — a prefix engineered to land exactly on a 128-byte block boundary, the single most favorable alignment for an attacker — confirmed to mismatch the true value there too, before the general-length version above went live.

Pitfalls

A shorter output is not a truncation of a longer one — demonstrated live above, not just asserted. BLAKE2b at 32 bytes and BLAKE2b at 64 bytes on the identical message and key are two different computations, not one digest cut short: the output length is XORed into h[0] before a single message byte is processed, so it changes the entire mixing from the first round onward. This is the opposite of SHA-512/256, which really is the first 256 bits of a run of SHA-512 with a different initial vector chosen specifically to make that truncation safe. Picking a short output here for compactness has a real cost, not just a cosmetic one: collision resistance is roughly half the output's bit length by the birthday bound, same as every hash on this site, so a 16-byte output only buys about 2⁶⁴ collision resistance — a level real cryptanalysis has already beaten for other hashes at comparable strength — where the default 64-byte output buys roughly 2²⁵⁶. Pick the output length for the security margin actually needed, not the shortest hex string that looks tidy.

The 64-byte key limit is a hard cutoff, not a "hash it down first" fallback. HMAC accepts a key of any length by hashing an over-long one down to the underlying hash's own output size first. BLAKE2b has no equivalent step: the key-length field in its parameter block is a single byte wide, so keys are capped at 64 bytes by construction. Python's own hashlib.blake2b raises an exception outright for a 65-byte key rather than silently hashing it down — confirmed directly against this page's own verification run, not assumed from the spec alone. A caller used to HMAC's forgiving behavior who passes an arbitrarily long key here will get a hard error, not a quietly-adjusted key.

A built-in keyed mode is not the same credential as HMAC's security proof. HMAC's security reduces to a generic, hash-agnostic argument (Bellare–Canetti–Krawczyk) that holds for essentially any underlying compression function with reasonable properties — it doesn't rely on anything specific to SHA-256. BLAKE2's own keyed-mode security argument is specific to BLAKE2's own design (the parameter-block domain separation and the finalization flag together), analyzed by its designers and widely trusted in practice, but it isn't the same kind of hash-agnostic reduction. That's not a reason to distrust it — it's a reason existing protocols that already specify HMAC don't swap it out just because a faster, built-in alternative exists next door. Where BLAKE2b actually gets used today is mostly as an internal primitive inside a larger, independently-analyzed construction — exactly the role it plays inside Argon2, still unbuilt here.

Verifying a MAC still needs a constant-time comparison. Same pitfall HMAC's own page names: a byte-by-byte comparison that returns on the first mismatch leaks timing information an attacker can exploit one byte at a time. Nothing about BLAKE2b's own construction changes that — it's a property of how the verifier compares two tags, not of the hash function underneath.

Complexity

Time: O(n) — one pass over the input, 12 rounds of fixed-cost mixing per 128-byte block, double SHA-256's own 64-byte block size. Measured once in plain Node, outside any sandbox (per this site's own standing caution against sourcing timing numbers from inside a vm context): Node's native blake2b512 ran about 9.8ms for 2,000 hashes of 1,000-byte messages against native sha256's 18.4ms for the same work — consistent with BLAKE2b's design intent of beating SHA-256 on real 64-bit hardware. That comparison isn't reproduced as a live widget on this page: this page's own reference implementation uses BigInt for every 64-bit word, which carries real interpreter overhead a native 64-bit CPU register doesn't, and running it side by side against SHA-256's own plain-32-bit-integer JavaScript would show BLAKE2b several dozen times slower in this environment specifically — the opposite of the real, native-code relationship, and exactly the kind of misleading number this site declines to ship live (the same discipline behind the deferred SharedArrayBuffer widget on Peterson's Algorithm's own page). Space: O(1) beyond the input — an 8-word running state and a 16-word message block, both reused block to block regardless of input length. Security: for the default 64-byte output, preimage resistance is roughly 2⁵¹² and collision resistance roughly 2²⁵⁶ by the birthday bound — the same relationship SHA-256's own Complexity section derives, just scaled to whatever output length is chosen instead of a single fixed width (see Pitfalls above). No attack against full-round BLAKE2b is known to beat generic brute force as of this writing.