Shamir's Secret Sharing — PHP 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 PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* secret-sharing — Shamir's Secret Sharing over GF(256), the Galois field of
* 256 elements.
*
* Language: PHP 7.4+ (standard library only).
* CosmoDev polyglot showcase port of the `secret-sharing` tool, ported from
* src/lib/secret-sharing.ts (the canonical TypeScript implementation).
*
* PHP strings are raw byte buffers, so a UTF-8 secret is already the exact byte
* sequence the scheme operates on; random_bytes() supplies the polynomial
* coefficients — the core-PHP stand-in for Web Crypto's getRandomValues.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
declare(strict_types=1);
/** Multiply by 2 (x) in GF(256), reducing by 0x11B - the AES "xtime". */
function xtime(int $a): int
{
return (($a << 1) ^ (($a & 0x80) !== 0 ? 0x11b : 0)) & 0xff;
}
/** Log/exp tables ([$exp, $log]) built once from generator 3: $exp[i] = 3^i. */
function gf_tables(): array
{
static $tables = null;
if ($tables !== null) { return $tables;}
$exp = array_fill(0, 256, 0);
$log = array_fill(0, 256, 0);
$x = 1;
for ($i = 0; $i < 255; $i++) {
$exp[$i] = $x;
$log[$x] = $i;
$x = ($x ^ xtime($x)) & 0xff; // step to the next power of the generator 3: x *= 3
}
$exp[255] = 1; // 3 has order 255, so EXP wraps: EXP[255] === EXP[0]
return $tables = [$exp, $log];
}
/** Multiply two field elements via log/exp tables; addition is XOR. */
function gf_mul(int $a, int $b): int
{
if ($a === 0 || $b === 0) { return 0;}
[$exp, $log] = gf_tables();
return $exp[($log[$a] + $log[$b]) % 255];
}
/** Divide a by b in GF(256). */
function gf_div(int $a, int $b): int
{
if ($b === 0) { throw new RuntimeException('Division by zero in GF(256)');}
if ($a === 0) { return 0;}
[$exp, $log] = gf_tables();
return $exp[($log[$a] + 255 - $log[$b]) % 255];
}
/** Evaluate a polynomial (coeffs[0] = constant term) at x, Horner style. */
function eval_poly(array $coeffs, int $x): int
{
$y = 0;
for ($i = count($coeffs) - 1; $i >= 0; $i--) {
$y = gf_mul($y, $x) ^ $coeffs[$i];
}
return $y;
}
/** Lagrange interpolation at x = 0 - subtraction is XOR, so (0 - xm) = xm and
* (xj - xm) = xj ^ xm; recovers the polynomial's constant term. */
function interpolate_at_zero(array $points): int
{
$result = 0;
foreach ($points as $j => [$xj, $yj]) {
$weight = 1;
foreach ($points as $m => [$xm, $ym]) {
if ($m !== $j) {
$weight = gf_mul($weight, gf_div($xm, $xj ^ $xm));
}
}
$result = gf_mul($yj, $weight) ^ $result;
}
return $result;
}
/**
* 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.
*
* @param callable(int): string|null $getRandomBytes injectable for tests
* @return string[]
* @throws InvalidArgumentException on out-of-range arguments
*/
function splitSecret(string $secret, int $totalShares, int $threshold, ?callable $getRandomBytes = null): array
{
if ($threshold < 2) { throw new InvalidArgumentException('Threshold must be at least 2 (a 1-of-N split is just the secret itself)');}
if ($totalShares > 255) { throw new InvalidArgumentException('Total shares must be at most 255 (share x-coordinates live in 1..255)');}
if ($threshold > $totalShares) { throw new InvalidArgumentException("Threshold ({$threshold}) cannot exceed total shares ({$totalShares})");}
$rand = $getRandomBytes ?? static fn (int $n): string => random_bytes($n);
$yParts = array_fill(0, $totalShares, str_repeat("\x00", strlen($secret)));
for ($b = 0, $len = strlen($secret); $b < $len; $b++) {
$coeffs = [ord($secret[$b])];
$random = $rand($threshold - 1); // fresh random coefficients per secret byte
for ($c = 1; $c < $threshold; $c++) {
$coeffs[$c] = ord($random[$c - 1]);
}
for ($i = 1; $i <= $totalShares; $i++) {
$yParts[$i - 1][$b] = chr(eval_poly($coeffs, $i));
}
}
$shares = [];
foreach ($yParts as $idx => $ys) {
$shares[] = sprintf('%02x-%s', $idx + 1, bin2hex($ys));
}
return $shares;
}
/**
* Parse one "xx-hex" share string.
*
* @return array{0: int, 1: string} the x-coordinate and the raw payload bytes
* @throws InvalidArgumentException on any malformed input
*/
function parseShare(string $share): array
{
$s = trim($share);
if (strlen($s) < 3 || $s[2] !== '-' || !ctype_xdigit(substr($s, 0, 2))) { throw new InvalidArgumentException("Malformed share \"{$s}\" - expected the format \"xx-hex…\" (e.g. \"01-a3b2c1\")");}
$yHex = substr($s, 3);
if (strlen($yHex) % 2 !== 0 || ($yHex !== '' && !ctype_xdigit($yHex))) { throw new InvalidArgumentException("Malformed share \"{$s}\" - the payload must be an even-length hex string");}
$x = (int) hexdec(substr($s, 0, 2));
if ($x === 0) { throw new InvalidArgumentException('Share x-coordinate 00 is invalid - shares are numbered from 01');}
return [$x, (string) hex2bin($yHex)];
}
/**
* 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 of the scheme, not a bug.
*
* @param string[] $shares
* @throws InvalidArgumentException on malformed or mismatched shares
*/
function reconstructSecret(array $shares): string
{
if (count($shares) < 2) { throw new InvalidArgumentException('Need at least 2 shares to reconstruct');}
$byX = [];
foreach ($shares as $share) {
[$x, $y] = parseShare($share);
if (!isset($byX[$x])) {
$byX[$x] = $y; // same share pasted twice dedupes
} elseif ($byX[$x] !== $y) {
throw new InvalidArgumentException(sprintf('Two different shares both claim x=%02x - they cannot come from the same split', $x));
}
}
ksort($byX); // lib sorts points by x before interpolating
if (count($byX) < 2) { throw new InvalidArgumentException('Need at least 2 distinct shares to reconstruct');}
$len = strlen((string) reset($byX));
foreach ($byX as $y) {
if (strlen($y) !== $len) {
throw new InvalidArgumentException('All shares must be the same length - they do not come from the same split');
}
}
$out = str_repeat("\x00", $len);
for ($b = 0; $b < $len; $b++) {
$points = [];
foreach ($byX as $x => $y) {
$points[] = [$x, ord($y[$b])];
}
$out[$b] = chr(interpolate_at_zero($points));
}
if (preg_match('//u', $out) !== 1) { throw new RuntimeException('Reconstructed bytes are not valid UTF-8 (the TS port throws in TextDecoder)');}
return $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 →