Shamir's Secret Sharing — Rust 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 Rust 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: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `secret-sharing` tool, ported from
//! src/lib/secret-sharing.ts (the canonical TypeScript implementation).
//!
//! Rust `String` is guaranteed UTF-8, so `String::from_utf8` plays the role of
//! TextDecoder. std has no CSPRNG, so polynomial coefficients come from a
//! SplitMix64 stream seeded by `RandomState` (OS entropy) plus the clock —
//! the closest std-only stand-in for `crypto.getRandomValues`.
use std::collections::hash_map::RandomState;
use std::collections::BTreeMap;
use std::hash::{BuildHasher, Hasher};
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};
/// Log/exp tables built once from the generator 3: exp[i] = 3^i, log[3^i] = i.
fn tables() -> &'static ([u8; 256], [u8; 256]) {
static T: OnceLock<([u8; 256], [u8; 256])> = OnceLock::new();
T.get_or_init(|| {
let (mut exp, mut log) = ([0u8; 256], [0u8; 256]);
let mut x: u8 = 1;
for i in 0..255 {
exp[i] = x;
log[x as usize] = i as u8;
x = (x ^ ((x << 1) ^ if x & 0x80 != 0 { 0x1b } else { 0 })) & 0xff; // x *= 3: x ^ xtime(x)
}
exp[255] = 1; // 3 has order 255, so EXP wraps: EXP[255] == EXP[0]
(exp, log)
})
}
/// Multiply two field elements via log/exp tables; addition is XOR.
fn gf_mul(a: u8, b: u8) -> u8 {
if a == 0 || b == 0 { return 0;}
let (exp, log) = tables();
exp[(((log[a as usize] as u16) + (log[b as usize] as u16)) % 255) as usize]
}
/// Divide a by b in GF(256); panics on b == 0 where the TS port throws.
fn gf_div(a: u8, b: u8) -> u8 {
if b == 0 { panic!("Division by zero in GF(256)");}
if a == 0 { return 0;}
let (exp, log) = tables();
exp[((log[a as usize] as usize + 255 - log[b as usize] as usize) % 255) as usize]
}
/// Evaluate a polynomial (coeffs[0] = constant term) at x, Horner style.
fn eval_poly(coeffs: &[u8], x: u8) -> u8 {
coeffs.iter().rev().fold(0u8, |y, &c| gf_mul(y, x) ^ c)
}
/// Lagrange interpolation at x = 0 (subtraction is XOR: 0-xm = xm, xj-xm = xj^xm),
/// recovering the polynomial's constant term from distinct-x points.
fn interpolate_at_zero(points: &[(u8, u8)]) -> u8 {
points.iter().fold(0u8, |result, &(xj, yj)| {
let weight = points.iter().fold(1u8, |w, &(xm, _)| if xm != xj { gf_mul(w, gf_div(xm, xj ^ xm)) } else { w });
result ^ gf_mul(yj, weight)
})
}
/// std-only randomness: SplitMix64 seeded from RandomState (randomized by the
/// OS per process) mixed with the wall clock. Not a CSPRNG — the substitute
/// promised in the header note.
struct SplitMix64(u64);
impl SplitMix64 {
fn new() -> Self {
let mut h = RandomState::new().build_hasher();
h.write_u64(SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0));
SplitMix64(h.finish())
}
fn fill(&mut self, out: &mut [u8]) {
for chunk in out.chunks_mut(8) {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
chunk.copy_from_slice(&(z ^ (z >> 31)).to_le_bytes()[..chunk.len()]);
}
}
}
/// A parsed share: its x-coordinate and its per-byte polynomial evaluations.
pub struct ParsedShare {
pub x: u8,
pub y: Vec<u8>,
}
/// Parse one "xx-hex" share string; errors on any malformed input.
pub fn parse_share(share: &str) -> Result<ParsedShare, String> {
let s = share.trim();
let bad_format = || format!("Malformed share \"{s}\" - expected the format \"xx-hex…\" (e.g. \"01-a3b2c1\")");
if s.len() < 3 || !s.is_ascii() || s.as_bytes()[2] != b'-' || !s[..2].bytes().all(|c| c.is_ascii_hexdigit()) { return Err(bad_format());}
let y_hex = &s[3..];
if y_hex.len() % 2 != 0 || !y_hex.bytes().all(|c| c.is_ascii_hexdigit()) { return Err(format!("Malformed share \"{s}\" - the payload must be an even-length hex string"));}
let x = u8::from_str_radix(&s[..2], 16).unwrap();
if x == 0 { return Err("Share x-coordinate 00 is invalid - shares are numbered from 01".into());}
let y: Vec<u8> = (0..y_hex.len()).step_by(2).map(|i| u8::from_str_radix(&y_hex[i..i + 2], 16).unwrap()).collect();
Ok(ParsedShare { x, y })
}
/// 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,
/// one hex byte per secret byte). `get_random_bytes` aids deterministic tests.
pub fn split_secret(
secret: &str,
total_shares: usize,
threshold: usize,
mut get_random_bytes: Option<&mut dyn FnMut(usize) -> Vec<u8>>,
) -> Result<Vec<String>, String> {
if threshold < 2 { return Err("Threshold must be at least 2 (a 1-of-N split is just the secret itself)".into());}
if total_shares > 255 { return Err("Total shares must be at most 255 (share x-coordinates live in 1..255)".into());}
if threshold > total_shares { return Err(format!("Threshold ({threshold}) cannot exceed total shares ({total_shares})"));}
let bytes = secret.as_bytes();
let mut fallback = SplitMix64::new();
let mut y_parts = vec![vec![0u8; bytes.len()]; total_shares];
let mut coeffs = vec![0u8; threshold];
for (b, &byte) in bytes.iter().enumerate() {
coeffs[0] = byte;
let random = match get_random_bytes.as_deref_mut() {
Some(f) => f(threshold - 1),
None => {
let mut buf = vec![0u8; threshold - 1];
fallback.fill(&mut buf);
buf
}
};
coeffs[1..].copy_from_slice(&random); // fresh random coefficients per secret byte
for (i, ys) in y_parts.iter_mut().enumerate() {
ys[b] = eval_poly(&coeffs, (i + 1) as u8);
}
}
Ok(y_parts
.iter()
.enumerate()
.map(|(i, ys)| format!("{:02x}-{}", i + 1, ys.iter().map(|b| format!("{b:02x}")).collect::<String>()))
.collect())
}
/// 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.
pub fn reconstruct_secret(shares: &[String]) -> Result<String, String> {
if shares.len() < 2 { return Err("Need at least 2 shares to reconstruct".into());}
let mut by_x: BTreeMap<u8, Vec<u8>> = BTreeMap::new(); // keeps shares sorted by x
for share in shares {
let p = parse_share(share)?;
// Same share pasted twice dedupes; a colliding x with another payload
// cannot belong to one split.
if let Some(prev_y) = by_x.insert(p.x, p.y.clone()) {
if prev_y != p.y {
return Err(format!("Two different shares both claim x={:02x} - they cannot come from the same split", p.x));
}
}
}
if by_x.len() < 2 { return Err("Need at least 2 distinct shares to reconstruct".into());}
let len = by_x.values().next().unwrap().len();
if by_x.values().any(|y| y.len() != len) { return Err("All shares must be the same length - they do not come from the same split".into());}
let points: Vec<(u8, &Vec<u8>)> = by_x.iter().map(|(&x, y)| (x, y)).collect();
let out: Vec<u8> = (0..len)
.map(|b| interpolate_at_zero(&points.iter().map(|&(x, y)| (x, y[b])).collect::<Vec<_>>()))
.collect();
String::from_utf8(out).map_err(|_| "Reconstructed bytes are not valid UTF-8".to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn splits_and_reconstructs() {
let shares = split_secret("héllo ✨ CosmoDev", 5, 3, None).unwrap();
assert_eq!(shares.len(), 5);
assert_eq!(reconstruct_secret(&shares[1..4]).unwrap(), "héllo ✨ CosmoDev");
assert!(reconstruct_secret(&shares[..1]).is_err());
assert!(parse_share("zz-deadbeef").is_err());
}
}
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 →