// A World's signing key drawn from its seed (ctx.signingKey; architecture, "What a handler writes with"): the same seed // and label give the same pair, so a World that issues it again (after a reset, ADR 0029 "Keys and generated secrets are // retained World state") issues the key its application already holds. Ed25519's private key is its 32-byte seed; an // RSA pair is generated as usual (two 1024-bit primes, e = 65537), its candidates drawn from an HMAC-SHA256 stream of // the seed instead of the platform's random source. import * as nodeCrypto from 'node:crypto'; export type SeededKeyPair = { privatePem: string; publicPem: string }; /** The seed's byte stream under a label: HMAC-SHA256(seed, label:counter), block after block. */ function byteStream(seed: string, label: string): (n: number) => Uint8Array { let counter = 0; let held = new Uint8Array(0); return (n) => { while (held.length < n) { const block = nodeCrypto.createHmac('sha256', seed).update(`${label}:${counter++}`).digest(); const next = new Uint8Array(held.length + block.length); next.set(held); next.set(block, held.length); held = next; } const out = held.slice(0, n); held = held.slice(n); return out; }; } const toBig = (bytes: Uint8Array): bigint => BigInt(`0x${Buffer.from(bytes).toString('hex') || '0'}`); function modPow(base: bigint, exponent: bigint, modulus: bigint): bigint { let result = 1n; let b = base % modulus; let e = exponent; while (e > 0n) { if (e & 1n) result = (result * b) % modulus; b = (b * b) % modulus; e >>= 1n; } return result; } function modInverse(a: bigint, m: bigint): bigint { let [oldR, r] = [((a % m) + m) % m, m]; let [oldS, s] = [1n, 0n]; while (r !== 0n) { const q = oldR / r; [oldR, r] = [r, oldR - q * r]; [oldS, s] = [s, oldS - q * s]; } if (oldR !== 1n) throw new Error('seeded key: no inverse'); return ((oldS % m) + m) % m; } const SMALL_PRIMES: bigint[] = (() => { const out: bigint[] = []; for (let n = 3; n < 2000; n += 2) if (out.every((p) => n % Number(p) !== 0)) out.push(BigInt(n)); return out; })(); /** Miller-Rabin with bases drawn from the stream: a composite passes 32 rounds with probability below 2^-64. */ function probablyPrime(n: bigint, draw: (n: number) => Uint8Array, bytes: number): boolean { for (const p of SMALL_PRIMES) if (n % p === 0n) return n === p; let d = n - 1n; let s = 0; while ((d & 1n) === 0n) { d >>= 1n; s++; } for (let round = 0; round < 32; round++) { const a = 2n + (toBig(draw(bytes)) % (n - 3n)); let x = modPow(a, d, n); if (x === 1n || x === n - 1n) continue; let composite = true; for (let i = 1; i < s; i++) { x = (x * x) % n; if (x === n - 1n) { composite = false; break; } } if (composite) return false; } return true; } /** The first prime the stream gives of `bits` bits, its top two bits set (so two of them make a modulus of exactly * twice the bits) and p - 1 coprime to e. */ function seededPrime(draw: (n: number) => Uint8Array, bits: number, e: bigint): bigint { const bytes = bits / 8; for (;;) { const candidate = toBig(draw(bytes)) | (3n << BigInt(bits - 2)) | 1n; if ((candidate - 1n) % e === 0n) continue; if (probablyPrime(candidate, draw, bytes)) return candidate; } } const b64url = (n: bigint): string => { let hex = n.toString(16); if (hex.length % 2) hex = `0${hex}`; return Buffer.from(hex, 'hex').toString('base64url'); }; const pem = (kind: string, der: ArrayBuffer): string => `-----BEGIN ${kind}-----\n${Buffer.from(der).toString('base64').replace(/(.{64})/g, '$1\n').replace(/\n$/, '')}\n-----END ${kind}-----\n`; /** The pair as PEMs, through WebCrypto (as the pairs made at random before were): the private key's PKCS #8, the * public key's SPKI. */ async function pems(jwk: JsonWebKey, algorithm: RsaHashedImportParams | { name: 'Ed25519' }): Promise { const subtle = globalThis.crypto.subtle; const privateKey = await subtle.importKey('jwk', jwk, algorithm, true, ['sign']); const { d: _d, p: _p, q: _q, dp: _dp, dq: _dq, qi: _qi, key_ops: _ops, ...publicJwk } = jwk; const publicKey = await subtle.importKey('jwk', publicJwk, algorithm, true, ['verify']); return { privatePem: pem('PRIVATE KEY', await subtle.exportKey('pkcs8', privateKey)), publicPem: pem('PUBLIC KEY', await subtle.exportKey('spki', publicKey)) }; } /** The pair a seed gives under a label: RSA-2048 (RS256) or Ed25519. */ export async function seededKeyPair(seed: string, label: string, alg: 'RS256' | 'Ed25519'): Promise { const draw = byteStream(seed, `signing-key:${alg}:${label}`); if (alg === 'Ed25519') { // an Ed25519 private key is its 32-byte seed; its public key is derived from it (RFC 8032 ยง5.1.5) const der = new Uint8Array([...Buffer.from('302e020100300506032b657004220420', 'hex'), ...draw(32)]); const imported = await globalThis.crypto.subtle.importKey('pkcs8', der, { name: 'Ed25519' }, true, ['sign']); return pems(await globalThis.crypto.subtle.exportKey('jwk', imported), { name: 'Ed25519' }); } const e = 65537n; let p = seededPrime(draw, 1024, e); let q = seededPrime(draw, 1024, e); while (q === p) q = seededPrime(draw, 1024, e); if (p < q) [p, q] = [q, p]; const n = p * q; const d = modInverse(e, (p - 1n) * (q - 1n)); return pems({ kty: 'RSA', n: b64url(n), e: b64url(e), d: b64url(d), p: b64url(p), q: b64url(q), dp: b64url(d % (p - 1n)), dq: b64url(d % (q - 1n)), qi: b64url(modInverse(q, p)), ext: true }, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }); }