nish/crypto/aes

AES-128 and AES-256 (FIPS 197), GCM on top of them (NIST SP 800-38D), and QUIC's AES header-protection mask (RFC 9001 §5.4.3).

import {
  AES_BLOCK,
  AES_GCM_TAG_SIZE,
  AesKey,
  aesBitslicedRound,
  aesEncryptBlock,
  aesGcmOpen,
  aesGcmSeal,
  aesGcmTagMask,
  aesHeaderMask,
  aesKey,
  aesKeyInto,
  aesKeyWipe,
  ghashMultiply,
} from "nish/crypto/aes";
import { aesKey, aesGcmSeal, aesGcmOpen, aesKeyWipe } from "nish/crypto/aes";

const key = aesKey(keyBytes); // 16 or 32 bytes, else null
if (key !== null) {
  // never seal two messages under one key with the same IV
  const sealed: u8[] | null = aesGcmSeal(key, iv, aad, plaintext);
  const opened: u8[] | null = sealed === null ? null : aesGcmOpen(key, iv, aad, sealed);
  aesKeyWipe(key);
}

Written from the specifications and the papers below, in this module's own layout, with one exception: ghashMul32 is adapted from BearSSL's bmul64, and carries BearSSL's notice. Nothing else here is ported from another implementation.

  • Bitslicing is the idea of E. Käsper and P. Schwabe, "Faster and Timing-Attack Resistant AES-GCM" (CHES 2009): hold bit b of many bytes in one word, so that SubBytes is a Boolean circuit run on whole words and no byte ever becomes a table index.
  • The S-box circuit is J. Boyar and R. Peralta's, "A depth-16 circuit for the AES S-box" (SEC 2012) and the 113-gate listing published with it: a linear layer in, 32 ANDs over GF(2^4) and GF(2^2) arithmetic, a linear layer out. aesSbox keeps their variable names so it can be read against the paper, gate by gate.
  • GHASH's multiply is carry-less multiplication done with the integer multiplier, by leaving three zero bits of "holes" between the bits of each operand so that the carries of an integer product land where nothing is read — T. Pornin's technique, and ghashMul32 is his bmul64 from BearSSL narrowed to 32-bit operands — with Karatsuba's three-for-four split on top (this module's own), and the reduction of S. Gueron and M. Kounavis, "Intel Carry-Less Multiplication Instruction and its Usage for Computing the GCM Mode" (2010), for GCM's bit-reflected field.
The bitsliced state

Four blocks at a time sit in eight u64 words, q[0..7], word b holding bit b of all 64 bytes. Inside a word, block k owns the 16 bits from 16k, and in those the byte in row r and column c of the AES state is bit 4r + c: each row is one nibble. That makes the two permutations cheap.

ShiftRows turns row r by r columns, which is a rotation of nibble r by r bits; MixColumns needs each byte's neighbour in the next row of its column, which is the word rotated by four bits inside each 16-bit lane. Getting 64 bytes in and out of that layout is an 8 × 8 bit-matrix transpose per byte lane (aesTranspose, three rounds of masked swaps between words) after placing each byte in the word and slot the transpose will carry to its bit (aesPack, aesUnpack).

Constant time

No table is read anywhere, key schedule included: the S-box is the circuit, and SubWord in the key schedule runs the same circuit on a four-byte state. No branch or index depends on a key, a plaintext, a tag or H: every if and every loop bound is on a length, a block number or the round count.

GHASH multiplies with no table and no data-dependent shift, and aesGcmOpen computes the whole tag and compares it with aesGcmTagMask — a difference ORed into one word and handed to ctEq — before it decrypts or returns anything. What tests/ct-asm.js verifies by disassembly on x86-64 and aarch64 is one full round (aesBitslicedRound: S-box circuit, ShiftRows, MixColumns, AddRoundKey), one GHASH multiply (ghashMultiply) and the tag compare (aesGcmTagMask).

A golden case compiles to one module and cannot import this one, so tests/cases/ct_asm_aes holds a verbatim copy of those three and the helpers they call, and tests/link/crypto_aes checks that the copy and this module agree on generated inputs, so neither can drift from the other unnoticed. Everything around them — packing bytes, the key schedule, the loops over blocks — is the discipline above and not a verified property.

The seams

Four private functions do nearly all of the cipher's work, each called from exactly one place: aesScheduleInto (the key schedule), aesBlockInto (one block), aesCtrInto (GCTR over a run of bytes) and ghashBlocksInto (GHASH over a run of bytes). Each takes the arrays its caller passes, writes into them and allocates nothing the caller needs back, and its one caller checks every precondition it names first.

That is what lets the compiler, natively, put each of those four calls behind a branch on the runtime's nish_aes_hw (src/kernels.ts, lowered in src/emit.ts): on a CPU with AES-NI and PCLMULQDQ, or the ARMv8 AES and PMULL instructions, the call goes to a kernel in runtime/runtime-aes.c that does no bounds checks of its own; on any other CPU, under NISH_AES=soft, on wasm32 and under Node, the body here runs (WP38 S5, docs/wp38-simd.md). The bodies are the bitsliced code, and keep their own defensive checks. The kernel keeps its own layout in a key's roundKeys, which a process only ever reads under the one answer nish_aes_hw gives it.

What runs outside the seams, and so on the bitsliced code whichever way they go: ghashLengths, the last GHASH block of every tag, and so the end of J0's derivation for an IV that is not 12 bytes, multiplies with ghashMultiply on the state a seam left; and aesGcmTag folds E(K, J0) into it. A kernel therefore leaves the GHASH state in this module's own form, two big-endian words, and tests/link/crypto_aes_agree holds the two paths to the same bytes on the IVs that take that road.

What is refused. A key of any length but 16 or 32 bytes (AES-192 is out of scope), a block or a sample that is not 16 bytes, an empty IV (SP 800-38D §5.2.1.1 asks for at least one bit), a sealed input shorter than its tag, a plaintext too long for its sealed form to be an array, and an AesKey aesKey did not make answer null; so does a tag that does not verify. An IV of any other non-zero length is hashed into the first counter block as §7.1 says.

Private names carry the aes / ghash prefix because a std/ module's private functions share the importing program's flat symbol namespace (docs/wp26-stdlib.md §3e).

Functions

aesBitslicedRound

One full middle round of the cipher on bitsliced state — SubBytes, ShiftRows, MixColumns, then the round key of eight words from at — for four blocks at once. Straight-line code with no branch and no index but at, which is a round number times eight. Exported so that tests/link/crypto_aes can hold the copy the disassembly check reads to this one; a caller has no other use for it.

const aesBitslicedRound: (
  q: u64[],
  rk: u64[],
  at: i32,
) => void
qu64[]required

The bitsliced state of four blocks, eight words, updated in place.

rku64[]required

The bitsliced round keys.

ati32required

Where this round's eight words start in rk.

aesEncryptBlock

One block encrypted (FIPS 197 §5.1, ECB): 16 bytes in, 16 fresh bytes out, or null for another length.

const aesEncryptBlock: (
  key: AesKey,
  block: u8[],
) => u8[] | null
keyAesKeyrequired

The expanded key.

blocku8[]required

The 16 bytes to encrypt; it is read, not kept.

returnsu8[] | null

A fresh 16-byte block, or null for another length or a key aesKey would not make.

aesGcmOpen

GCM authenticated decryption (SP 800-38D §7.2): sealed is the ciphertext followed by its 16-byte tag, and the answer is the plaintext, or null when the tag does not verify, the IV is empty, sealed is shorter than a tag or the key is not one aesKey made. The tag is computed over the received ciphertext and compared in constant time before anything is decrypted, so a forgery yields no plaintext at all.

const aesGcmOpen: (
  key: AesKey,
  iv: u8[],
  aad: u8[],
  sealed: u8[],
) => u8[] | null
keyAesKeyrequired

The expanded key.

ivu8[]required

The nonce the message was sealed with.

aadu8[]required

The data authenticated with it; must match what was sealed.

sealedu8[]required

The ciphertext followed by its 16-byte tag.

returnsu8[] | null

A fresh array holding the plaintext, or null if the tag fails or the input is bad.

aesGcmSeal

GCM authenticated encryption (SP 800-38D §7.1): the ciphertext followed by the 16-byte tag, in one fresh array. The IV may be any non-zero length; 12 bytes is the fast and usual one. null for an empty IV, for a key aesKey did not make, and for a plaintext longer than 2^31 - 17 bytes, whose sealed form would not fit in an array.

const aesGcmSeal: (
  key: AesKey,
  iv: u8[],
  aad: u8[],
  plaintext: u8[],
) => u8[] | null
keyAesKeyrequired

The expanded key.

ivu8[]required

The nonce, any non-zero length; it must never repeat under one key.

aadu8[]required

Data authenticated but not encrypted; may be empty.

plaintextu8[]required

The message to encrypt; it is read, not kept.

returnsu8[] | null

A fresh array of ciphertext then tag, plaintext.length + 16 bytes, or null for bad input.

aesGcmTagMask

All-ones when the tag tagHi:tagLo equals gotHi:gotLo, zero otherwise: the difference of both halves ORed into one word and handed to ctEq, so every bit of both tags is read and nothing is branched on until the caller tests the one answer. Exported, like aesBitslicedRound, so the disassembly check's copy can be held to it.

const aesGcmTagMask: (
  tagHi: u64,
  tagLo: u64,
  gotHi: u64,
  gotLo: u64,
) => u64
tagHiu64required

The high half of the expected tag.

tagLou64required

The low half of the expected tag.

gotHiu64required

The high half of the received tag.

gotLou64required

The low half of the received tag.

returnsu64

All-ones if the tags match, zero if they do not.

aesHeaderMask

The AES header-protection mask of RFC 9001 §5.4.3: the first five bytes of the 16-byte sample encrypted under the header-protection key. null for a sample of another length.

const aesHeaderMask: (
  key: AesKey,
  sample: u8[],
) => u8[] | null
keyAesKeyrequired

The header-protection key.

sampleu8[]required

The 16 bytes sampled from the packet's ciphertext.

returnsu8[] | null

A fresh 5-byte mask, or null for another sample length or a key aesKey would not make.

aesKey

Makes an AesKey from 16 bytes (AES-128) or 32 (AES-256): the key schedule, bitsliced, and H = E(K, 0^128) for GCM. Any other length — 24 bytes included, since AES-192 is not offered — answers null.

const aesKey: (key: u8[]) => AesKey | null
keyu8[]required

The raw key, 16 or 32 bytes; it is read, not kept, and the caller still wipes it.

returnsAesKey | null

A fresh key, which the caller hands to aesKeyWipe when done, or null for another length.

aesKeyInto

aesKey into an AesKey the caller already holds: the key schedule of a 16-byte (AES-128) or 32-byte (AES-256) key, bitsliced, and H = E(K, 0^128) for GCM, written into out, whose roundKeys must already be the 8 * (rounds + 1) words that key length needs (88 or 120). It answers whether it did; a key of another length, or a schedule array of the wrong size for it (or an h that is not two words), answers false and leaves out as it was.

aesKey makes a fresh AesKey and stores its schedule into it, which no arena scope may be put around; this stores numbers only, so a caller that keeps one AesKey per connection installs every key inside a using a = arena() block and leaves the arena where it was. The schedule and H are secret: the caller hands out to aesKeyWipe when it is done with the key.

The schedule is written straight into out.roundKeys, and the working copies the bitsliced schedule and the block H passes through are wiped with wipe's volatile stores before they are released. On a CPU that runs the runtime's kernels (the seams, in the module docs) those copies are the kernels' own, in runtime/runtime-aes.c, and what they leave in vector registers no wipe here reaches.

aesKey makes its key through this, so this is the one call of aesScheduleInto, and the checks its contract needs are made here.

const aesKeyInto: (key: u8[], out: AesKey) => boolean
keyu8[]required

The raw key, 16 or 32 bytes; it is read, not kept, and the caller still wipes it.

outAesKeyrequired

The key to overwrite, its roundKeys sized for this key length.

returnsboolean

true if out now holds the key; false if it was left as it was.

aesKeyWipe

Zeroes everything secret key holds — every word of roundKeys, the runtime kernels' powers of H after the schedule included, and h — with wipe's volatile stores, which no optimiser removes however dead the key is about to be. rounds is not secret and stays. A wiped key seals under an all-zero schedule and, its H being zero, opens nothing (aesGcmOpen); aesKeyInto installs a new key into it.

const aesKeyWipe: (key: AesKey) => void
keyAesKeyrequired

The key to wipe; it stays usable as an aesKeyInto target.

ghashMultiply

GHASH's multiply (SP 800-38D §6.3), y = y · H in GF(2^128), with y as two words y[0] (high) and y[1] (low) of the block read big-endian and H likewise in hHi and hLo.

GCM numbers a block's bits from the first, so the block read big-endian is the polynomial with its coefficients reversed. The carry-less product of two reversed polynomials is the reversed product one bit short, so the 256-bit product is shifted left once, and then its low half — the coefficients of x^128 and up — is folded into the high half by x^128 = x^7 + x^2 + x + 1, in two steps because the fold of the lowest seven bits lands back in the low half (Gueron and Kounavis, §4 of the paper cited in the header).

The 128 × 128 product is Karatsuba twice over: three 64 × 64 products, each of three 32 × 32 ones from ghashMul32. Straight-line code; exported, like aesBitslicedRound, so the disassembly check's copy can be held to it.

const ghashMultiply: (y: u64[], hHi: u64, hLo: u64) => void
yu64[]required

The running GHASH value, two words, multiplied in place.

hHiu64required

The high half of H.

hLou64required

The low half of H.

Classes

AesKey

An AES key, expanded: the round keys already bitsliced, and GCM's hash key H = E(K, 0^128), so a key used for many messages is expanded once.

Make one with aesKey. The constructor and the fields are public only because tests build keys by hand and read their words, and a key built or edited by hand is not trusted: one whose shape is not what aesKey makes answers null everywhere (aesKeyUsable), and one whose H is zero opens nothing (aesGcmOpen). On the runtime kernels' path GHASH takes H and its powers from roundKeys, while ghashLengths and a non-12-byte IV's J0 take it from h; aesKey writes both from one schedule, so they agree. A key edited so that they disagree is outside the contract, and what it seals then depends on which path the process runs.

Both are secret. A holder done with a key hands it to aesKeyWipe, whose volatile stores zero all of roundKeys (the kernels' tail of H's powers included) and h, and stand however dead the key is about to be.

class AesKey
Member
new AesKey(rounds: i32, roundKeys: u64[]) Wraps a schedule array and allocates h; neither is filled. aesKey calls this and then fills both, and a caller makes keys with aesKey.
h: u64[] H as a big-endian 128-bit number, two words: h[0] the high half and h[1] the low. An array rather than two scalar fields, so that aesKeyWipe's volatile wipe reaches it.
roundKeys: u64[] Round key i in the bitsliced layout, replicated into all four block lanes, as eight words from 8 * i: 8 * (rounds + 1) words in all. In a native process that runs the runtime's AES kernels (the seams, above), the same words hold the kernels' layout instead, runtime/runtime-aes.c's.
rounds: i32 Nr: 10 for AES-128, 14 for AES-256.

Constants

16

AES_BLOCK: i32

The AES block, in bytes.

16

AES_GCM_TAG_SIZE: i32

GCM's tag, in bytes: this module makes and accepts only the full 128 bits.