SPB Git

Repository Public

primitives.ts 6.2 KB 108 lines typescript

1// SPV1 suite 1 primitives over WebCrypto and @hpke/core. No primitive is implemented here.2import { Aes256Gcm, CipherSuite, DhkemP256HkdfSha256, HkdfSha256 } from "@hpke/core";3import { type Bytes, b64u, concat, unb64u } from "./bytes.ts";45const subtle = crypto.subtle;6const B = (b: Bytes) => b as unknown as BufferSource;7const EC = { name: "ECDH", namedCurve: "P-256" } as const;8const DSA = { name: "ECDSA", namedCurve: "P-256" } as const;910export const sha256 = async (b: Bytes): Promise<Bytes> => new Uint8Array(await subtle.digest("SHA-256", B(b)));1112export async function hkdf(ikm: Bytes, salt: Bytes, info: Bytes, length = 32): Promise<Bytes> {13  const k = await subtle.importKey("raw", B(ikm), "HKDF", false, ["deriveBits"]);14  return new Uint8Array(await subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: B(salt), info: B(info) }, k, length * 8));15}1617export async function hmac(key: Bytes, msg: Bytes): Promise<Bytes> {18  const k = await subtle.importKey("raw", B(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);19  return new Uint8Array(await subtle.sign("HMAC", k, B(msg)));20}2122async function aesKey(key: Bytes, use: KeyUsage): Promise<CryptoKey> {23  if (key.length !== 32) throw new Error("AES-256 key must be 32 bytes");24  return subtle.importKey("raw", B(key), "AES-GCM", false, [use]);25}2627/** AES-256-GCM; returns ciphertext‖tag. Nonce must be 12 bytes and unique per key. */28export async function aeadSeal(key: Bytes, nonce: Bytes, plaintext: Bytes, aad: Bytes): Promise<Bytes> {29  if (nonce.length !== 12) throw new Error("nonce must be 12 bytes");30  return new Uint8Array(await subtle.encrypt({ name: "AES-GCM", iv: B(nonce), additionalData: B(aad), tagLength: 128 }, await aesKey(key, "encrypt"), B(plaintext)));31}3233export async function aeadOpen(key: Bytes, nonce: Bytes, ciphertext: Bytes, aad: Bytes): Promise<Bytes> {34  if (nonce.length !== 12) throw new Error("nonce must be 12 bytes");35  if (ciphertext.length < 16) throw new Error("ciphertext too short");36  try {37    return new Uint8Array(await subtle.decrypt({ name: "AES-GCM", iv: B(nonce), additionalData: B(aad), tagLength: 128 }, await aesKey(key, "decrypt"), B(ciphertext)));38  } catch { throw new Error("authentication failed"); }39}4041// ── P-256 keys ────────────────────────────────────────────────────────────────────────────────────────────────4243export interface KeyPair { privateKey: CryptoKey; publicKey: CryptoKey; pub: Bytes }4445function checkPub(pub: Bytes) { if (pub.length !== 65 || pub[0] !== 4) throw new Error("public key must be a 65-byte X9.63 point"); }4647export async function generateKemKey(extractable: boolean): Promise<KeyPair> {48  const kp = await subtle.generateKey(EC, extractable, ["deriveBits"]);49  return { ...kp, pub: new Uint8Array(await subtle.exportKey("raw", kp.publicKey)) };50}51export async function generateSigKey(extractable: boolean): Promise<KeyPair> {52  const kp = await subtle.generateKey(DSA, extractable, ["sign", "verify"]);53  return { ...kp, pub: new Uint8Array(await subtle.exportKey("raw", kp.publicKey)) };54}5556/** X9.63 private representation: 04‖X‖Y‖D (97 bytes). */57export async function exportPrivateX963(key: CryptoKey): Promise<Bytes> {58  const jwk = await subtle.exportKey("jwk", key);59  return concat(new Uint8Array([4]), unb64u(jwk.x!), unb64u(jwk.y!), unb64u(jwk.d!));60}6162export async function importPrivateX963(raw: Bytes, kind: "kem" | "sig", extractable = false): Promise<KeyPair> {63  if (raw.length !== 97 || raw[0] !== 4) throw new Error("private key must be a 97-byte X9.63 representation");64  const jwk = { kty: "EC", crv: "P-256", x: b64u(raw.subarray(1, 33)), y: b64u(raw.subarray(33, 65)), d: b64u(raw.subarray(65, 97)) };65  const alg = kind === "kem" ? EC : DSA;66  const privateKey = await subtle.importKey("jwk", jwk, alg, extractable, kind === "kem" ? ["deriveBits"] : ["sign"]);67  const pub = raw.slice(0, 65);68  const publicKey = await subtle.importKey("raw", B(pub), alg, true, kind === "kem" ? [] : ["verify"]);69  return { privateKey, publicKey, pub };70}7172// ── ECDSA P-256 / SHA-256, raw r‖s ────────────────────────────────────────────────────────────────────────────7374export async function sign(key: CryptoKey, msg: Bytes): Promise<Bytes> {75  return new Uint8Array(await subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, B(msg)));76}7778export async function verify(pub: Bytes, msg: Bytes, sig: Bytes): Promise<boolean> {79  checkPub(pub);80  if (sig.length !== 64) return false;81  const k = await subtle.importKey("raw", B(pub), DSA, false, ["verify"]);82  return subtle.verify({ name: "ECDSA", hash: "SHA-256" }, k, B(sig), B(msg));83}8485// ── HPKE base mode, DHKEM(P-256,HKDF-SHA256) / HKDF-SHA256 / AES-256-GCM ─────────────────────────────────────8687const suite = new CipherSuite({ kem: new DhkemP256HkdfSha256(), kdf: new HkdfSha256(), aead: new Aes256Gcm() });88const ENC_LEN = 65;8990/** Returns enc(65) ‖ ciphertext. */91export async function hpkeSeal(recipientPub: Bytes, info: Bytes, plaintext: Bytes): Promise<Bytes> {92  checkPub(recipientPub);93  const pk = await subtle.importKey("raw", B(recipientPub), EC, true, []);94  const { ct, enc } = await suite.seal({ recipientPublicKey: pk, info: B(info) as ArrayBuffer }, B(plaintext) as ArrayBuffer);95  return concat(new Uint8Array(enc), new Uint8Array(ct));96}9798export async function hpkeOpen(recipient: { privateKey: CryptoKey; publicKey: CryptoKey }, info: Bytes, sealed: Bytes): Promise<Bytes> {99  if (sealed.length < ENC_LEN + 16) throw new Error("sealed box too short");100  try {101    const pt = await suite.open(102      { recipientKey: { privateKey: recipient.privateKey, publicKey: recipient.publicKey }, enc: B(sealed.slice(0, ENC_LEN)) as ArrayBuffer, info: B(info) as ArrayBuffer },103      B(sealed.slice(ENC_LEN)) as ArrayBuffer,104    );105    return new Uint8Array(pt);106  } catch { throw new Error("authentication failed"); }107}108
Files main
Menu

Theme