Skip to content

Shamir's Secret Sharing — Python 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 Python 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: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `secret-sharing` tool, ported from
src/lib/secret-sharing.ts (the canonical TypeScript implementation).

Addition in GF(256) is XOR; multiplication rides discrete log/exp tables built
from the generator 3 under AES' reduction polynomial 0x11B. ``secrets`` supplies
the random polynomial coefficients — the stdlib stand-in for Web Crypto.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import re
import secrets

# GF256_EXP[i] = 3^i in GF(256); GF256_LOG[3^i] = i (GF256_LOG[0] is unused).
GF256_EXP = [0] * 256
GF256_LOG = [0] * 256

_x = 1
for _i in range(255):
    GF256_EXP[_i] = _x
    GF256_LOG[_x] = _i
    _x ^= ((_x << 1) ^ (0x11B if _x & 0x80 else 0)) & 0xFF  # AES xtime step: x *= 3
GF256_EXP[255] = 1  # 3 has order 255, so EXP wraps: EXP[255] == EXP[0]


def gf_mul(a: int, b: int) -> int:
    """Multiply two field elements via log/exp tables; addition is XOR."""
    if a == 0 or b == 0:
        return 0
    return GF256_EXP[(GF256_LOG[a] + GF256_LOG[b]) % 255]


def gf_div(a: int, b: int) -> int:
    """Divide a by b in GF(256)."""
    if b == 0:
        raise ValueError("Division by zero in GF(256)")
    if a == 0:
        return 0
    return GF256_EXP[(GF256_LOG[a] + 255 - GF256_LOG[b]) % 255]


def eval_poly(coeffs: list[int], x: int) -> int:
    """Evaluate a polynomial (coeffs[0] = constant term) at x, Horner style."""
    y = 0
    for coeff in reversed(coeffs):
        y = gf_mul(y, x) ^ coeff
    return y


def interpolate_at_zero(points: list[tuple[int, int]]) -> int:
    """Lagrange interpolation at x = 0 (subtraction is XOR: 0-xm = xm, xj-xm = xj^xm)."""
    result = 0
    for j, (xj, yj) in enumerate(points):
        weight = 1
        for m, (xm, _ym) in enumerate(points):
            if m != j:
                weight = gf_mul(weight, gf_div(xm, xj ^ xm))
        result ^= gf_mul(yj, weight)
    return result


def split_secret(secret: str, total_shares: int, threshold: int, get_random_bytes=None) -> list[str]:
    """Split a secret into total_shares shares (x = 1..N) where any threshold of
    them reconstruct it; returns "xx-hex..." strings (hex x-coordinate, dash,
    then one hex byte per secret byte). ``get_random_bytes`` aids testing.
    """
    for name, v in (("Total shares", total_shares), ("Threshold", threshold)):
        if not isinstance(v, int):
            raise TypeError(f"{name} must be an integer (got {v})")
    if threshold < 2:
        raise ValueError("Threshold must be at least 2 (a 1-of-N split is just the secret itself)")
    if total_shares > 255:
        raise ValueError("Total shares must be at most 255 (share x-coordinates live in 1..255)")
    if threshold > total_shares:
        raise ValueError(f"Threshold ({threshold}) cannot exceed total shares ({total_shares})")
    data = secret.encode("utf-8")
    rand = get_random_bytes or secrets.token_bytes
    y_parts = [bytearray(len(data)) for _ in range(total_shares)]
    for b, byte in enumerate(data):
        coeffs = [byte] + list(rand(threshold - 1))  # fresh coefficients per byte
        for i in range(1, total_shares + 1):
            y_parts[i - 1][b] = eval_poly(coeffs, i)
    return [f"{idx + 1:02x}-{bytes(ys).hex()}" for idx, ys in enumerate(y_parts)]


def parse_share(share: str) -> tuple[int, bytes]:
    """Parse one "xx-hex" share string; raises ValueError on malformed input."""
    s = share.strip()
    if len(s) < 3 or s[2] != "-" or not re.fullmatch(r"[0-9a-fA-F]{2}", s[:2]):
        raise ValueError(f'Malformed share "{s}" - expected the format "xx-hex…" (e.g. "01-a3b2c1")')
    y_hex = s[3:]
    if len(y_hex) % 2 != 0 or not re.fullmatch(r"[0-9a-fA-F]*", y_hex):
        raise ValueError(f'Malformed share "{s}" - the payload must be an even-length hex string')
    x = int(s[:2], 16)
    if x == 0:
        raise ValueError("Share x-coordinate 00 is invalid - shares are numbered from 01")
    return x, bytes.fromhex(y_hex)


def reconstruct_secret(shares: list[str]) -> str:
    """Reconstruct the secret from share strings; needs at least 2 distinct shares.
    Fewer than the true threshold K yields garbage without warning - the security
    property of the scheme, not a bug."""
    if len(shares) < 2:
        raise ValueError("Need at least 2 shares to reconstruct")
    by_x: dict[int, bytes] = {}
    for share in shares:
        x, y = parse_share(share)
        existing = by_x.get(x)
        if existing is None:
            by_x[x] = y
        elif existing != y:  # same share twice dedupes; colliding x = broken split
            raise ValueError(f"Two different shares both claim x={x:02x} - they cannot come from the same split")
    points = sorted(by_x.items())
    if len(points) < 2:
        raise ValueError("Need at least 2 distinct shares to reconstruct")
    length = len(points[0][1])
    if any(len(y) != length for _, y in points):
        raise ValueError("All shares must be the same length - they do not come from the same split")
    out = bytearray(length)
    for b in range(length):
        out[b] = interpolate_at_zero([(x, y[b]) for x, y in points])
    return out.decode("utf-8")

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 →