Shamir's Secret Sharing — Go 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 Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package secretsharing ports src/lib/secret-sharing.ts (dual source: the web
// lib is TypeScript, the CLI lib is Go — kept in lock-step). Shamir's Secret
// Sharing over GF(256), pure math with zero dependencies beyond the stdlib.
//
// Addition in GF(256) is XOR; multiplication uses discrete log/exp tables
// built from the generator 3 (0x03) under the same reduction polynomial as
// AES (x^8 + x^4 + x^3 + x + 1 = 0x11B).
//
// Split: for each byte of the secret, build a random polynomial of degree
// K-1 whose constant term is the secret byte, then evaluate it at x = 1..N.
// Reconstruct: with K or more shares, Lagrange interpolation at x = 0
// recovers each constant term. Fewer than K shares reveal nothing
// (information-theoretic security).
//
// Behavior parity with the TS lib: same inputs → same outputs, same error
// messages (the TS suite's /regex/ assertions map to substring checks here).
// The table-driven tests in secret_sharing_test.go share vectors with
// src/lib/secret-sharing.test.ts so the two implementations are held to the
// same contract. Two TS test vectors are structurally N/A in Go: the
// non-integer-parameter check (Go parameters are typed ints) and the
// "Web Crypto unavailable" check (crypto/rand is always available).
package secretsharing
import (
"bytes"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"sort"
"strconv"
"strings"
)
// GF256Exp is the exponent table: GF256Exp[i] = 3^i in GF(256). Index 255
// mirrors index 0. Mirrors GF256_EXP in the TS lib.
var GF256Exp [256]byte
// GF256Log is the discrete log table: GF256Log[3^i] = i (GF256Log[0] is
// unused). Mirrors GF256_LOG in the TS lib.
var GF256Log [256]byte
func init() {
x := byte(1)
for i := 0; i < 255; i++ {
GF256Exp[i] = x
GF256Log[x] = byte(i)
// step to the next power of the generator 3: x *= 3 (i.e. x ^ xtime(x))
x ^= Xtime(x)
}
// 3 has order 255, so EXP wraps: EXP[255] === EXP[0].
GF256Exp[255] = 1
}
// Xtime multiplies by 2 (x) in GF(256), reducing by 0x11B — the AES "xtime".
// It mirrors xtime() in the TS lib.
func Xtime(a byte) byte {
b := a << 1
if a&0x80 != 0 {
b ^= 0x1b // (0x11b & 0xff), the low byte of the reduction polynomial
}
return b
}
// GfAdd is addition in GF(256): bitwise XOR (also serves as subtraction).
func GfAdd(a, b byte) byte {
return a ^ b
}
// GfMul multiplies two field elements via the log/exp tables.
func GfMul(a, b byte) byte {
if a == 0 || b == 0 {
return 0
}
return GF256Exp[(int(GF256Log[a])+int(GF256Log[b]))%255]
}
// GfInv returns the multiplicative inverse of a non-zero element.
func GfInv(a byte) (byte, error) {
if a == 0 {
return 0, errors.New("0 has no multiplicative inverse in GF(256)")
}
return GF256Exp[(255-int(GF256Log[a]))%255], nil
}
// GfDiv divides a by b in GF(256).
func GfDiv(a, b byte) (byte, error) {
if b == 0 {
return 0, errors.New("Division by zero in GF(256)")
}
if a == 0 {
return 0, nil
}
return GF256Exp[(int(GF256Log[a])+255-int(GF256Log[b]))%255], nil
}
// EvalPoly evaluates a polynomial (coeffs[0] = constant term) at x,
// Horner style. Mirrors evalPoly() in the TS lib.
func EvalPoly(coeffs []byte, x byte) byte {
var y byte
for i := len(coeffs) - 1; i >= 0; i-- {
y = GfAdd(GfMul(y, x), coeffs[i])
}
return y
}
// Point is one (x, y) evaluation used by Lagrange interpolation. It stands in
// for the TS lib's Array<[number, number]> tuples.
type Point struct {
X byte
Y byte
}
// InterpolateAtZero Lagrange-interpolates at x = 0 over distinct-x points —
// recovering the polynomial's constant term. Subtraction is XOR, so
// (0 - xm) = xm and (xj - xm) = xj ^ xm. Duplicate x-coordinates are a
// division by zero and return an error (the TS lib throws).
func InterpolateAtZero(points []Point) (byte, error) {
var result byte
for j := range points {
weight := byte(1)
for m := range points {
if m == j {
continue
}
d, err := GfDiv(points[m].X, points[j].X^points[m].X)
if err != nil {
return 0, fmt.Errorf("interpolation requires distinct x-coordinates: %w", err)
}
weight = GfMul(weight, d)
}
result = GfAdd(result, GfMul(points[j].Y, weight))
}
return result, nil
}
// SplitOptions configures SplitSecret. GetRandomBytes is injectable for
// deterministic tests; the zero value (nil function) uses crypto/rand — the
// Go stand-in for the TS lib's Web Crypto default.
type SplitOptions struct {
GetRandomBytes func(n int) ([]byte, error)
}
func defaultRandomBytes(n int) ([]byte, error) {
buf := make([]byte, n)
if _, err := rand.Read(buf); err != nil {
return nil, err
}
return buf, nil
}
// SplitSecret splits a secret into totalShares shares (x = 1..N) where any
// threshold of them reconstructs it. It returns hex share strings like
// "01-a3b2c1..." — the two-digit hex x-coordinate, a dash, then one hex byte
// per secret byte. The secret is encoded as UTF-8, matching the TS lib's
// TextEncoder. It mirrors splitSecret() in the TS lib.
func SplitSecret(secret string, totalShares, threshold int, opts *SplitOptions) ([]string, error) {
if threshold < 2 {
return nil, errors.New("Threshold must be at least 2 (a 1-of-N split is just the secret itself)")
}
if totalShares > 255 {
return nil, errors.New("Total shares must be at most 255 (share x-coordinates live in 1..255)")
}
if threshold > totalShares {
return nil, fmt.Errorf("Threshold (%d) cannot exceed total shares (%d)", threshold, totalShares)
}
randomBytes := defaultRandomBytes
if opts != nil && opts.GetRandomBytes != nil {
randomBytes = opts.GetRandomBytes
}
secretBytes := []byte(secret)
yParts := make([][]byte, totalShares)
for i := range yParts {
yParts[i] = make([]byte, len(secretBytes))
}
coeffs := make([]byte, threshold)
for b := 0; b < len(secretBytes); b++ {
coeffs[0] = secretBytes[b]
if threshold > 1 {
rnd, err := randomBytes(threshold - 1)
if err != nil {
return nil, fmt.Errorf("random source failed: %w", err)
}
copy(coeffs[1:], rnd)
}
for i := 1; i <= totalShares; i++ {
yParts[i-1][b] = EvalPoly(coeffs, byte(i))
}
}
shares := make([]string, totalShares)
for idx, ys := range yParts {
shares[idx] = fmt.Sprintf("%02x-%s", idx+1, hex.EncodeToString(ys))
}
return shares, nil
}
// ParsedShare is one parsed share: its x-coordinate and its per-byte
// polynomial evaluations. Mirrors the ParsedShare interface in the TS lib.
type ParsedShare struct {
X int
Y []byte
}
func isHexDigits(s string) bool {
for i := 0; i < len(s); i++ {
c := s[i]
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F') {
return false
}
}
return true
}
// ParseShare parses one "xx-hex" share string; it errors on any malformed
// input. Whitespace is trimmed and uppercase hex is accepted, exactly like
// parseShare() in the TS lib.
func ParseShare(share string) (ParsedShare, error) {
s := strings.TrimSpace(share)
if len(s) < 3 || s[2] != '-' || !isHexDigits(s[0:2]) {
return ParsedShare{}, fmt.Errorf("Malformed share %q - expected the format \"xx-hex…\" (e.g. \"01-a3b2c1\")", s)
}
yHex := s[3:]
if !isHexDigits(yHex) || len(yHex)%2 != 0 {
return ParsedShare{}, fmt.Errorf("Malformed share %q - the payload must be an even-length hex string", s)
}
y, err := hex.DecodeString(yHex)
if err != nil {
return ParsedShare{}, fmt.Errorf("Malformed share %q - the payload must be an even-length hex string", s)
}
x, err := strconv.ParseUint(s[0:2], 16, 8)
if err != nil {
return ParsedShare{}, fmt.Errorf("Malformed share %q - expected the format \"xx-hex…\" (e.g. \"01-a3b2c1\")", s)
}
if x == 0 {
return ParsedShare{}, errors.New("Share x-coordinate 00 is invalid - shares are numbered from 01")
}
return ParsedShare{X: int(x), Y: y}, nil
}
// ReconstructSecret reconstructs the secret from an arbitrary collection of
// share strings. It needs at least 2 distinct shares (the threshold of the
// original split); anything less than the true threshold K yields garbage
// without warning — that is the security property of the scheme, not a bug.
// It mirrors reconstructSecret() in the TS lib.
func ReconstructSecret(shares []string) (string, error) {
if len(shares) < 2 {
return "", errors.New("Need at least 2 shares to reconstruct")
}
byX := make(map[int][]byte, len(shares))
for _, share := range shares {
parsed, err := ParseShare(share)
if err != nil {
return "", err
}
// The same share pasted twice is harmless (dedupe); a colliding
// x-coordinate with a different payload cannot belong to one split.
if existing, ok := byX[parsed.X]; !ok {
byX[parsed.X] = parsed.Y
} else if !bytes.Equal(existing, parsed.Y) {
return "", fmt.Errorf("Two different shares both claim x=%02x - they cannot come from the same split", parsed.X)
}
}
xs := make([]int, 0, len(byX))
for x := range byX {
xs = append(xs, x)
}
sort.Ints(xs)
if len(xs) < 2 {
return "", errors.New("Need at least 2 distinct shares to reconstruct")
}
length := len(byX[xs[0]])
for _, x := range xs {
if len(byX[x]) != length {
return "", errors.New("All shares must be the same length - they do not come from the same split")
}
}
out := make([]byte, length)
pair := make([]Point, len(xs))
for i, x := range xs {
pair[i] = Point{X: byte(x)}
}
for b := 0; b < length; b++ {
for i := range pair {
pair[i].Y = byX[xs[i]][b]
}
v, err := InterpolateAtZero(pair)
if err != nil {
return "", err
}
out[b] = v
}
return string(out), nil
}
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 →