/** * Shamir's Secret Sharing over GF(2^8), byte by byte — the scheme behind SLIP-39 and most seed * splitters. k-of-n: any k shares rebuild the secret; k−1 shares reveal nothing at all (every * candidate secret is equally consistent with them). Runs on the device only. * * Share text format ("cbseed1-…"): version, share index, threshold and the share bytes, base32 * encoded with a CRC-16 so a typo is caught before it produces a wrong phrase. */ // ---- GF(2^8) with the AES polynomial (x^8 + x^4 + x^3 + x + 1) ---- const EXP = new Uint8Array(512); const LOG = new Uint8Array(256); (() => { let x = 1; for (let i = 0; i < 255; i++) { EXP[i] = x; LOG[x] = i; // multiply by the generator 3 x ^= (x << 1) ^ ((x & 0x80) ? 0x11b : 0); x &= 0xff; } for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255]; })(); const mul = (a: number, b: number): number => (a === 0 || b === 0 ? 0 : EXP[LOG[a] + LOG[b]]); const div = (a: number, b: number): number => { if (b === 0) throw new Error('division by zero'); return a === 0 ? 0 : EXP[(LOG[a] + 255 - LOG[b]) % 255]; }; export interface Share { index: number; threshold: number; data: Uint8Array } /** Split `secret` into n shares of which any k reconstruct it. 2 ≤ k ≤ n ≤ 16. */ export function split(secret: Uint8Array, k: number, n: number): Share[] { if (!Number.isInteger(k) || !Number.isInteger(n) || k < 2 || n < k || n > 16) throw new Error('Choose a threshold of at least 2 and at most 16 shares.'); const shares: Share[] = Array.from({ length: n }, (_, i) => ({ index: i + 1, threshold: k, data: new Uint8Array(secret.length) })); const coeffs = new Uint8Array(k - 1); for (let b = 0; b < secret.length; b++) { crypto.getRandomValues(coeffs); // a fresh random polynomial per byte; the constant term is the secret byte for (const s of shares) { // Horner's rule: y = a0 + a1·x + … + a(k−1)·x^(k−1) let y = 0; for (let c = k - 2; c >= 0; c--) y = mul(y, s.index) ^ coeffs[c]; s.data[b] = mul(y, s.index) ^ secret[b]; } } return shares; } /** Rebuild the secret from at least `threshold` distinct shares (Lagrange interpolation at x = 0). */ export function combine(shares: Share[]): Uint8Array { const seen = new Map(); for (const s of shares) seen.set(s.index, s); const list = [...seen.values()]; if (list.length === 0) throw new Error('No shares given.'); const k = list[0].threshold; const len = list[0].data.length; if (list.some((s) => s.threshold !== k || s.data.length !== len)) throw new Error('These shares do not belong to the same split.'); if (list.length < k) throw new Error(`This split needs ${k} shares; ${list.length} given.`); const use = list.slice(0, k); const out = new Uint8Array(len); for (let b = 0; b < len; b++) { let acc = 0; for (const i of use) { let num = 1, den = 1; for (const j of use) { if (i === j) continue; num = mul(num, j.index); den = mul(den, i.index ^ j.index); } acc ^= mul(i.data[b], div(num, den)); } out[b] = acc; } return out; } // ---- text encoding ---- const B32 = 'abcdefghijklmnopqrstuvwxyz234567'; function toBase32(bytes: Uint8Array): string { let bits = 0, value = 0, out = ''; for (const byte of bytes) { value = (value << 8) | byte; bits += 8; while (bits >= 5) { out += B32[(value >>> (bits - 5)) & 31]; bits -= 5; } } if (bits > 0) out += B32[(value << (5 - bits)) & 31]; return out; } function fromBase32(s: string): Uint8Array { let bits = 0, value = 0; const out: number[] = []; for (const ch of s) { const v = B32.indexOf(ch); if (v < 0) throw new Error(`Unexpected character "${ch}" in a share.`); value = (value << 5) | v; bits += 5; if (bits >= 8) { out.push((value >>> (bits - 8)) & 0xff); bits -= 8; } } return new Uint8Array(out); } function crc16(bytes: Uint8Array): number { let crc = 0xffff; for (const b of bytes) { crc ^= b << 8; for (let i = 0; i < 8; i++) crc = crc & 0x8000 ? ((crc << 1) ^ 0x1021) & 0xffff : (crc << 1) & 0xffff; } return crc; } export const SHARE_PREFIX = 'cbseed1-'; /** "cbseed1-xxxx-xxxx-…": readable, typeable, checksummed. */ export function encodeShare(s: Share, prefix: string = SHARE_PREFIX): string { const body = new Uint8Array(3 + s.data.length + 2); body[0] = 1; body[1] = s.index; body[2] = s.threshold; body.set(s.data, 3); const crc = crc16(body.subarray(0, 3 + s.data.length)); body[3 + s.data.length] = crc >> 8; body[4 + s.data.length] = crc & 0xff; const text = toBase32(body); return prefix + (text.match(/.{1,4}/g) ?? []).join('-'); } /** Parse a share in any spacing/case; throws a plain-English error when it is not a valid share. */ export function decodeShare(input: string, expectedPrefix: string = SHARE_PREFIX): Share { const compact = input.trim().toLowerCase().replace(/[\s\-_]/g, ''); const prefix = expectedPrefix.replace('-', ''); if (!compact.startsWith(prefix)) throw new Error(`That does not look like a CapsuleBridge ${expectedPrefix === SHARE_PREFIX ? 'seed share' : 'recovery card'} (it should start with "${expectedPrefix}").`); const body = fromBase32(compact.slice(prefix.length)); if (body.length < 6 || body[0] !== 1) throw new Error('That share is incomplete.'); const payload = body.subarray(0, body.length - 2); const crc = (body[body.length - 2] << 8) | body[body.length - 1]; if (crc16(payload) !== crc) throw new Error('That share has a typo — check it against the card and try again.'); return { index: body[1], threshold: body[2], data: body.slice(3, body.length - 2) }; }