SPB Git

Repository Public

crypto.ts 8.9 KB 160 lines typescript

1/**2 * Cryptographic helpers for everything that is not MLS itself.3 * Only standard constructions from maintained libraries are used:4 *   Ed25519 (WebCrypto through ts-mls, public keys through @noble/curves), HPKE RFC 9180 (@hpke/core),5 *   HKDF-SHA256 and AES-256-GCM (WebCrypto). Nothing here invents a primitive.6 */7import { Aes256Gcm, CipherSuite, DhkemX25519HkdfSha256, HkdfSha256 } from "@hpke/core"8import { ed25519 } from "@noble/curves/ed25519.js"9import { b64, bs, concat, equalBytes, randomBytes, unb64, utf8, uuidBytes } from "./bytes"1011const subtle = crypto.subtle1213// ---------- Ed25519 ----------14function pkcs8(seed: Uint8Array) {15  return concat(new Uint8Array([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20]), seed)16}17export const edPublic = (seed: Uint8Array) => ed25519.getPublicKey(seed)18export async function edSign(seed: Uint8Array, message: Uint8Array): Promise<Uint8Array> {19  const key = await subtle.importKey("pkcs8", bs(pkcs8(seed)), "Ed25519", false, ["sign"])20  return new Uint8Array(await subtle.sign("Ed25519", key, bs(message)))21}22export async function edVerify(publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array): Promise<boolean> {23  try {24    const key = await subtle.importKey("raw", bs(publicKey), "Ed25519", false, ["verify"])25    return await subtle.verify("Ed25519", key, bs(signature), bs(message))26  } catch {27    return false28  }29}3031// ---------- device certificates: the account identity key vouches for each device key ----------32export const certMessage = (userId: string, deviceId: string, signatureKey: Uint8Array) =>33  concat(utf8("spm-device-cert-v1"), uuidBytes(userId), uuidBytes(deviceId), signatureKey)34export const signCert = (identitySeed: Uint8Array, userId: string, deviceId: string, signatureKey: Uint8Array) =>35  edSign(identitySeed, certMessage(userId, deviceId, signatureKey))36export const verifyCert = (identityKey: Uint8Array, userId: string, deviceId: string, signatureKey: Uint8Array, cert: Uint8Array) =>37  edVerify(identityKey, certMessage(userId, deviceId, signatureKey), cert)38export const sessionBindMessage = (sessionId: string, deviceId: string) => concat(utf8("spm-session-bind-v1"), uuidBytes(sessionId), uuidBytes(deviceId))3940// ---------- symmetric ----------41export async function hkdf(secret: Uint8Array, info: string, length = 32, salt: Uint8Array = new Uint8Array()): Promise<Uint8Array> {42  const key = await subtle.importKey("raw", bs(secret), "HKDF", false, ["deriveBits"])43  return new Uint8Array(await subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: bs(salt), info: bs(utf8(info)) }, key, length * 8))44}45export async function sha256(data: Uint8Array): Promise<Uint8Array> {46  return new Uint8Array(await subtle.digest("SHA-256", bs(data)))47}48const aesKey = (key: Uint8Array) => subtle.importKey("raw", bs(key), "AES-GCM", false, ["encrypt", "decrypt"])49/** AES-256-GCM with a random 96-bit nonce prepended to the ciphertext. */50export async function seal(key: Uint8Array, plaintext: Uint8Array, aad: Uint8Array = new Uint8Array()): Promise<Uint8Array> {51  const nonce = randomBytes(12)52  const ct = await subtle.encrypt({ name: "AES-GCM", iv: bs(nonce), additionalData: bs(aad) }, await aesKey(key), bs(plaintext))53  return concat(nonce, new Uint8Array(ct))54}55export async function open(key: Uint8Array, sealed: Uint8Array, aad: Uint8Array = new Uint8Array()): Promise<Uint8Array> {56  const pt = await subtle.decrypt({ name: "AES-GCM", iv: bs(sealed.subarray(0, 12)), additionalData: bs(aad) }, await aesKey(key), bs(sealed.subarray(12)))57  return new Uint8Array(pt)58}5960// ---------- HPKE (device enrolment: the identity key is sealed to the new device's one-time key) ----------61const suite = new CipherSuite({ kem: new DhkemX25519HkdfSha256(), kdf: new HkdfSha256(), aead: new Aes256Gcm() })62export async function linkKeygen(): Promise<{ publicKey: Uint8Array; privateKey: Uint8Array }> {63  const kp = await suite.kem.generateKeyPair()64  return {65    publicKey: new Uint8Array(await suite.kem.serializePublicKey(kp.publicKey)),66    privateKey: new Uint8Array(await suite.kem.serializePrivateKey(kp.privateKey)),67  }68}69export async function hpkeSeal(recipientPublic: Uint8Array, info: Uint8Array, plaintext: Uint8Array): Promise<Uint8Array> {70  const pk = await suite.kem.deserializePublicKey(bs(recipientPublic) as ArrayBuffer)71  const { ct, enc } = await suite.seal({ recipientPublicKey: pk, info: bs(info) as ArrayBuffer }, bs(plaintext) as ArrayBuffer)72  return concat(new Uint8Array(enc), new Uint8Array(ct))73}74export async function hpkeOpen(recipientPrivate: Uint8Array, info: Uint8Array, sealed: Uint8Array): Promise<Uint8Array> {75  const sk = await suite.kem.deserializePrivateKey(bs(recipientPrivate) as ArrayBuffer)76  const pt = await suite.open({ recipientKey: sk, enc: bs(sealed.subarray(0, 32)) as ArrayBuffer, info: bs(info) as ArrayBuffer }, bs(sealed.subarray(32)) as ArrayBuffer)77  return new Uint8Array(pt)78}79export const linkInfo = (userId: string, deviceId: string) => concat(utf8("spm-device-link-v1"), uuidBytes(userId), uuidBytes(deviceId))80/** Six-digit code both devices display; the person compares them before approving. */81export async function linkCode(userId: string, deviceId: string, linkPub: Uint8Array, signatureKey: Uint8Array): Promise<string> {82  const h = await sha256(concat(utf8("spm-link-code-v1"), uuidBytes(userId), uuidBytes(deviceId), linkPub, signatureKey))83  const n = ((h[0] << 24) | (h[1] << 16) | (h[2] << 8) | h[3]) >>> 084  return String(n % 1_000_000).padStart(6, "0")85}8687// ---------- recovery key and encrypted backup of the identity key ----------88const ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" // 32 symbols, no I/O/0/189/** 160 bits from the CSPRNG, shown as 8 groups of 4 characters. */90export function newRecoveryKey(): string {91  const raw = randomBytes(20)92  let bits = 0, acc = 0, out = ""93  for (const b of raw) {94    acc = (acc << 8) | b95    bits += 896    while (bits >= 5) {97      out += ALPHABET[(acc >>> (bits - 5)) & 31]98      bits -= 599    }100  }101  return out.match(/.{4}/g)!.join("-")102}103export function normalizeRecoveryKey(input: string): string {104  return input.toUpperCase().replace(/[^A-Z0-9]/g, "")105}106async function backupKey(recoveryKey: string, userId: string) {107  const canonical = recoveryKey.toUpperCase().replace(/[^A-Z0-9]/g, "")108  return hkdf(utf8(canonical), "spm-backup-v1", 32, uuidBytes(userId))109}110export async function sealBackup(recoveryKey: string, userId: string, identitySeed: Uint8Array): Promise<Uint8Array> {111  return seal(await backupKey(recoveryKey, userId), identitySeed, utf8("spm-backup-v1"))112}113export async function openBackup(recoveryKey: string, userId: string, blob: Uint8Array): Promise<Uint8Array> {114  return open(await backupKey(recoveryKey, userId), blob, utf8("spm-backup-v1"))115}116117// ---------- safety numbers ----------118/** Fingerprint of an identity key: 30 digits in 6 groups, derived from SHA-256(key ‖ user id). */119export async function fingerprint(identityKey: Uint8Array, userId: string): Promise<string> {120  const h = await sha256(concat(utf8("spm-fingerprint-v1"), uuidBytes(userId), identityKey))121  const groups: string[] = []122  for (let i = 0; i < 6; i++) {123    const n = ((h[i * 4] << 24) | (h[i * 4 + 1] << 16) | (h[i * 4 + 2] << 8) | h[i * 4 + 3]) >>> 0124    groups.push(String(n % 100000).padStart(5, "0"))125  }126  return groups.join(" ")127}128/** Number two people compare: both fingerprints, ordered so each side computes the same string. */129export async function safetyNumber(a: { id: string; key: Uint8Array }, b: { id: string; key: Uint8Array }): Promise<string> {130  const [x, y] = a.id < b.id ? [a, b] : [b, a]131  return `${await fingerprint(x.key, x.id)} ${await fingerprint(y.key, y.id)}`132}133134// ---------- attachments: chunked AES-256-GCM (one key per file, never sent outside an encrypted message) ----------135export const FILE_CHUNK = 1024 * 1024136export const TAG = 16137function chunkNonce(prefix: Uint8Array, index: number) {138  const n = new Uint8Array(12)139  n.set(prefix, 0)140  new DataView(n.buffer).setUint32(8, index)141  return n142}143function chunkAad(index: number, last: boolean) {144  const a = new Uint8Array(5)145  new DataView(a.buffer).setUint32(0, index)146  a[4] = last ? 1 : 0147  return a148}149/** Each chunk is bound to its position and to whether it is the final one, so chunks cannot be reordered, dropped or truncated. */150export async function encryptChunk(key: Uint8Array, prefix: Uint8Array, index: number, last: boolean, plaintext: Uint8Array): Promise<Uint8Array> {151  const ct = await subtle.encrypt({ name: "AES-GCM", iv: bs(chunkNonce(prefix, index)), additionalData: bs(chunkAad(index, last)) }, await aesKey(key), bs(plaintext))152  return new Uint8Array(ct)153}154export async function decryptChunk(key: Uint8Array, prefix: Uint8Array, index: number, last: boolean, ciphertext: Uint8Array): Promise<Uint8Array> {155  const pt = await subtle.decrypt({ name: "AES-GCM", iv: bs(chunkNonce(prefix, index)), additionalData: bs(chunkAad(index, last)) }, await aesKey(key), bs(ciphertext))156  return new Uint8Array(pt)157}158159export { b64, unb64, equalBytes }160
Files main
Menu

Theme