Shamir's Secret Sharing — JavaScript source
Split a secret into N shares where any K shares can reconstruct it — but fewer than K reveal nothing. Based on Shamir's threshold scheme over GF(256).
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* secret-sharing — Shamir's Secret Sharing over GF(256), the Galois field of
* 256 elements.
*
* Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
* CosmoDev polyglot showcase port of the `secret-sharing` tool, ported from
* src/lib/secret-sharing.ts (the canonical TypeScript implementation).
*
* Pure GF(256) math with information-theoretic security: fewer than K shares
* reveal literally nothing, and the whole tool fits in one dependency-free file.
*
* display source - part of CosmoDev's polyglot tool pages.
*/
// TextEncoder/TextDecoder and crypto.getRandomValues: globals in browsers and Node >= 16.
const encoder = new TextEncoder();
const decoder = new TextDecoder();
/** Exponent table GF256_EXP[i] = 3^i; discrete log GF256_LOG[3^i] = i. */
export const GF256_EXP = new Uint8Array(256);
export const GF256_LOG = new Uint8Array(256);
(function initTables() {
let x = 1;
for (let i = 0; i < 255; i++) {
GF256_EXP[i] = x;
GF256_LOG[x] = i;
// AES "xtime" by 2, XORed back in: step to the next power of generator 3.
x ^= ((x << 1) ^ (x & 0x80 ? 0x11b : 0)) & 0xff;
}
GF256_EXP[255] = 1; // 3 has order 255, so EXP wraps: EXP[255] === EXP[0]
})();
/** Multiply two field elements via log/exp tables; addition is XOR. */
export function gfMul(a, b) {
if (a === 0 || b === 0) return 0;
return GF256_EXP[(GF256_LOG[a] + GF256_LOG[b]) % 255];
}
/** Divide a by b in GF(256). */
export function gfDiv(a, b) {
if (b === 0) throw new Error('Division by zero in GF(256)');
if (a === 0) return 0;
return GF256_EXP[(GF256_LOG[a] + 255 - GF256_LOG[b]) % 255];
}
/** Evaluate a polynomial (coeffs[0] = constant term) at x, Horner style. */
export const evalPoly = (coeffs, x) => coeffs.reduceRight((y, c) => gfMul(y, x) ^ c, 0);
/** Lagrange interpolation at x = 0 - subtraction is XOR, so (0 - xm) = xm and
* (xj - xm) = xj ^ xm; recovers the polynomial's constant term. */
export function interpolateAtZero(points) {
let result = 0;
for (const [xj, yj] of points) {
let weight = 1;
for (const [xm] of points) if (xm !== xj) weight = gfMul(weight, gfDiv(xm, xj ^ xm));
result = gfMul(yj, weight) ^ result;
}
return result;
}
const toHex = (bytes) => [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
/**
* Split a secret into totalShares shares (x = 1..N) where any threshold of
* them reconstruct it. Returns hex share strings like "01-a3b2c1..." - the
* two-digit hex x-coordinate, a dash, then one hex byte per secret byte.
*/
export function splitSecret(secret, totalShares, threshold, opts) {
if (!Number.isInteger(totalShares)) throw new Error(`Total shares must be an integer (got ${totalShares})`);
if (!Number.isInteger(threshold)) throw new Error(`Threshold must be an integer (got ${threshold})`);
if (threshold < 2) throw new Error('Threshold must be at least 2 (a 1-of-N split is just the secret itself)');
if (totalShares > 255) throw new Error('Total shares must be at most 255 (share x-coordinates live in 1..255)');
if (threshold > totalShares) throw new Error(`Threshold (${threshold}) cannot exceed total shares (${totalShares})`);
const bytes = encoder.encode(secret);
const rand = opts?.getRandomBytes ?? ((n) => crypto.getRandomValues(new Uint8Array(n)));
const yParts = Array.from({ length: totalShares }, () => new Uint8Array(bytes.length));
const coeffs = new Uint8Array(threshold);
for (let b = 0; b < bytes.length; b++) {
coeffs[0] = bytes[b];
coeffs.set(rand(threshold - 1), 1); // fresh random coefficients per secret byte
for (let i = 1; i <= totalShares; i++) yParts[i - 1][b] = evalPoly(coeffs, i);
}
return yParts.map((ys, idx) => `${(idx + 1).toString(16).padStart(2, '0')}-${toHex(ys)}`);
}
/** Parse one "xx-hex" share string; throws on any malformed input. */
export function parseShare(share) {
const s = share.trim();
if (s.length < 3 || s[2] !== '-' || !/^[0-9a-fA-F]{2}$/.test(s.slice(0, 2)))
throw new Error(`Malformed share "${s}" - expected the format "xx-hex…" (e.g. "01-a3b2c1")`);
const yHex = s.slice(3);
if (!/^[0-9a-fA-F]*$/.test(yHex) || yHex.length % 2 !== 0)
throw new Error(`Malformed share "${s}" - the payload must be an even-length hex string`);
const x = parseInt(s.slice(0, 2), 16);
if (x === 0) throw new Error('Share x-coordinate 00 is invalid - shares are numbered from 01');
const y = new Uint8Array(yHex.length / 2);
for (let i = 0; i < y.length; i++) y[i] = parseInt(yHex.slice(i * 2, i * 2 + 2), 16);
return { x, y };
}
/**
* Reconstruct the secret from share strings; needs at least 2 distinct shares
* (the threshold of the original split). Fewer than the true threshold K
* yields garbage without warning - the security property, not a bug.
*/
export function reconstructSecret(shares) {
if (shares.length < 2) throw new Error('Need at least 2 shares to reconstruct');
const byX = new Map();
for (const share of shares) {
const { x, y } = parseShare(share);
const existing = byX.get(x);
if (existing === undefined) byX.set(x, y);
// Same share pasted twice dedupes; a colliding x with another payload cannot be one split.
else if (!existing.every((b, i) => b === y[i]))
throw new Error(`Two different shares both claim x=${x.toString(16).padStart(2, '0')} - they cannot come from the same split`);
}
const points = [...byX.entries()].sort((a, b) => a[0] - b[0]);
if (points.length < 2) throw new Error('Need at least 2 distinct shares to reconstruct');
const len = points[0][1].length;
if (points.some(([, y]) => y.length !== len))
throw new Error('All shares must be the same length - they do not come from the same split');
const out = new Uint8Array(len);
const pair = points.map(([x]) => [x, 0]);
for (let b = 0; b < len; b++) {
for (let i = 0; i < points.length; i++) pair[i][1] = points[i][1][b];
out[b] = interpolateAtZero(pair);
}
return decoder.decode(out);
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →