diff options
| author | Nicholas Rodrigues Lordello <[email protected]> | 2023-09-23 10:28:58 +0200 |
|---|---|---|
| committer | Nicholas Rodrigues Lordello <[email protected]> | 2025-04-01 08:52:25 +0200 |
| commit | e646e4bbe13b5b0603e9e8c8b062865afbb69d8d (patch) | |
| tree | 619b559db2746b4e09ae2b3b06b6b95ca0614ca0 | |
| parent | 241930146ee2e12264f307af5d45ae44a847553b (diff) | |
More shamir things
| -rw-r--r-- | src/shamir.rs | 204 | ||||
| -rw-r--r-- | src/shamir/secret.rs | 60 |
2 files changed, 203 insertions, 61 deletions
diff --git a/src/shamir.rs b/src/shamir.rs index 64be065..7329a71 100644 --- a/src/shamir.rs +++ b/src/shamir.rs @@ -9,111 +9,187 @@ use hmac::{Hmac, Mac as _}; use sha2::Sha256; mod ff; +mod secret; /// A single share for a secret. -pub struct Share {} +pub struct Share { + id: i16, + e: u8, + gi: u8, + gt: u8, + g: u8, + mi: u8, + mt: u8, + share: Vec<u8>, +} + +impl Share { + fn words(&self) -> impl Iterator<Item = i16> + '_ { + let radix = 10; + let bits = (self.share.len() * 8) as isize; + let n = (bits + radix - 1) / radix; + let padding = n - bits; + + (0..n).map(|i| { + //let bit_offset = i * radix; + i as _ + }) + } +} /// Lagrange interpolation of a polynomial at `x` described by the specified /// points. -fn interpolate<const N: usize>(x: u8, points: &[(u8, &[u8; N])]) -> [u8; N] { - let points = || points.iter().copied(); +fn interpolate(ps: &[(u8, &[u8])], x: u8, y: &mut [u8]) { + assert_lengths(y.len(), ps.iter().map(|(_, yi)| *yi)); - let mut y = [0; N]; - for (xi, yi) in points() { + let ps = || ps.iter().copied().enumerate(); + for (i, (xi, yi)) in ps() { let mut pi = 1; - for (xj, _) in points().filter(|(xj, _)| *xj != xi) { + for (j, (xj, _)) in ps().filter(|(j, _)| *j != i) { + debug_assert!(xi != xj, "duplicate point"); pi = ff::mul(pi, ff::div(ff::sub(x, xj), ff::sub(xi, xj))); } - for k in 0..N { - y[k] = ff::add(y[k], ff::mul(yi[k], pi)); + for (yk, yik) in y.iter_mut().zip(yi) { + *yk = ff::add(*yk, ff::mul(*yik, pi)); } } - y } /// Splits a secret into `n` shares, with a threshold recovery `t`. Returns a /// `Vec` with `n` elements representing each of the shares. -fn split_secret<const N: usize>(t: usize, n: usize, s: &[u8; N]) -> Vec<[u8; N]> { +fn split_secret(t: usize, n: usize, s: &[u8]) -> Vec<Vec<u8>> { + let m = s.len(); debug_assert!( - 0 < t && t <= n && n <= 16 && N >= 16 && N <= 36, + 0 < t && t <= n && n <= 16 && m >= 16 && m % 2 == 0, "invalid shamir parameters", ); if t == 1 { - return (0..n).map(|_| *s).collect(); + return (0..n).map(|_| s.to_vec()).collect(); } let d = { - let mut buf = [0; N]; + let mut buf = vec![0; m]; let r = &mut buf[4..]; rand::fill(r); - let mut mac = Hmac::<Sha256>::new_from_slice(r).expect("r is small enough"); - mac.update(s); - let code = mac.finalize().into_bytes(); + let code = hmac_sha256(r, s); buf[..4].copy_from_slice(&code[..4]); buf }; - let mut ys = vec![[0; N]; n]; + let mut ys = vec![vec![0; m]; n]; let (ysr, ysi) = ys.split_at_mut(t - 2); for y in ysr.iter_mut() { - rand::getentropy(y).expect("y is small enough"); + rand::fill(y.as_mut()); } - let points = ysr + let ps = ysr .iter() .enumerate() - .map(|(x, y)| (x as u8, y)) - .chain([(254, &d), (255, &s)]) + .map(|(x, y)| (x as u8, &y[..])) + .chain([(254, &d[..]), (255, s)]) .collect::<Vec<_>>(); for (i, y) in ysi.iter_mut().enumerate() { let x = i + t - 2; - *y = interpolate(x as _, &points) + interpolate(&ps, x as _, y); } ys } /// Recovers a secret from a list of shares for a threshold `t`. -fn recover_secret<const N: usize>(t: usize, ps: &[(u8, &[u8; N])]) -> Result<[u8; N]> { +fn recover_secret(ps: &[(u8, &[u8])]) -> Result<Vec<u8>> { + let t = ps.len(); + let m = ps.first().map(|(_, y)| y.len()).unwrap_or_default(); + assert_lengths(m, ps.iter().map(|(_, y)| *y)); debug_assert!( - 0 < t && t <= 16 && t <= ps.len() && N >= 16 && N <= 36, - "invalid shamir parameters", + 0 < t && t <= 16 && m >= 16 && m % 2 == 0, + "invalid shamir parameters" ); if t == 1 { - return Ok(*ps[0].1); + return Ok(ps[0].1.to_vec()); } - let s = interpolate(255, ps); - let d = interpolate(254, ps); + let (mut s, mut d) = (vec![0; m], vec![0; m]); - let code = { - let r = &d[4..]; - let mut mac = Hmac::<Sha256>::new_from_slice(r).expect("r is small enough"); - mac.update(&s); - mac.finalize().into_bytes() - }; + interpolate(ps, 255, &mut s); + interpolate(ps, 254, &mut d); - ensure!(d[..4] == code[..4], "secret checksum mismatch"); + let r = &d[4..]; + let code = hmac_sha256(r, &s[..]); + ensure!(d[..4] == code[..4], "secret checksum mismatch"); Ok(s) } +/// Generates shares for the given input. +fn generate_shares(gt: usize, g: &[(usize, usize)], s: &[u8], p: &[u8], e: u32) -> Vec<Share> { + debug_assert!( + !g.iter().any(|&(t, n)| t == 1 && n == 1) && e < 0x1f, + "invalid shamir paramters", + ); + + let id = { + let mut buf = [0; 2]; + rand::fill(&mut buf); + i16::from_be_bytes(buf) & 0x7fff + }; + + let es = secret::encrypt(s, p, e, id); + + split_secret(gt, g.len(), &es) + .iter() + .enumerate() + .zip(g) + .flat_map(|((gi, s), &(mt, mn))| { + split_secret(mt, mn, s) + .into_iter() + .enumerate() + .map(move |(mi, share)| Share { + id, + e: e as _, + gi: gi as _, + gt: gt as _, + g: g.len() as _, + mi: mi as _, + mt: mt as _, + share, + }) + }) + .collect() +} + +fn hmac_sha256(r: &[u8], s: &[u8]) -> [u8; 32] { + Hmac::<Sha256>::new_from_slice(r) + .expect("HMAC should accept arbitrary key sizes") + .chain_update(&s) + .finalize() + .into_bytes() + .into() +} + +fn assert_lengths<'a>(m: usize, mut ys: impl Iterator<Item = &'a [u8]>) { + debug_assert!( + ys.all(|y| y.len() == m), + "secret and shares have different lengths", + ); +} + #[cfg(test)] mod tests { use super::*; #[test] fn lagrange_interpolation() { - assert_eq!( - interpolate(0, &[(1, &[118, 56]), (2, &[146, 14])]), - [42, 42] - ); + let mut y = [0, 0]; + interpolate(&[(1, &[118, 56]), (2, &[146, 14])], 0, &mut y); + + assert_eq!(y, [42, 42]); } #[test] @@ -127,6 +203,11 @@ mod tests { }; let shares = split_secret(3, 5, &secret); + + // Insufficient shares + assert!(recover_secret(&[(0, &shares[0]), (1, &shares[1])]).is_err()); + + // Exact amount of shares for i in 0..5 { for j in 0..5 { for k in 0..5 { @@ -134,34 +215,35 @@ mod tests { continue; } - let recovered = recover_secret( - 3, - &[ - (i as _, &shares[i]), - (j as _, &shares[j]), - (k as _, &shares[k]), - ], - ) + let exact = recover_secret(&[ + (i as _, &shares[i]), + (j as _, &shares[j]), + (k as _, &shares[k]), + ]) .unwrap(); - assert_eq!(secret, recovered); + assert_eq!(secret[..], exact); } } } - let extra = recover_secret( - 3, - &[ - (0, &shares[0]), - (1, &shares[1]), - (2, &shares[2]), - (3, &shares[3]), - (4, &shares[4]), - ], - ) + // Extra shares + let extra = recover_secret(&[ + (0, &shares[0]), + (1, &shares[1]), + (2, &shares[2]), + (3, &shares[3]), + (4, &shares[4]), + ]) .unwrap(); - assert_eq!(secret, extra); + assert_eq!(secret[..], extra); + } + + #[test] + fn very_large_secret() { + let secret = [42; 8192]; + let shares = split_secret(2, 2, &secret); + let recovered = recover_secret(&[(0, &shares[0]), (1, &shares[1])]).unwrap(); - let missing = interpolate(255, &[(0, &shares[0]), (1, &shares[1])]); - assert_ne!(secret, missing); + assert_eq!(&secret[..], recovered); } } diff --git a/src/shamir/secret.rs b/src/shamir/secret.rs new file mode 100644 index 0000000..d2e8887 --- /dev/null +++ b/src/shamir/secret.rs @@ -0,0 +1,60 @@ +//! Implementation of SLIP-0039 secret encryption. + +use hmac::Hmac; +use sha2::Sha256; +use std::iter; + +/// Encrypts a secret using a 4-round Feistel cypher. +pub fn encrypt(s: &[u8], p: &[u8], e: u32, id: i16) -> Vec<u8> { + feistel(s, p, e, id, [0, 1, 2, 3]) +} + +/// Decrypts a secret using a 4-round Feistel cypher. +pub fn decrypt(es: &[u8], p: &[u8], e: u32, id: i16) -> Vec<u8> { + feistel(es, p, e, id, [3, 2, 1, 0]) +} + +fn feistel(m: &[u8], p: &[u8], e: u32, id: i16, instances: [u8; 4]) -> Vec<u8> { + let n = m.len() / 2; + debug_assert!(n * 2 == m.len(), "secret must be even number of bytes"); + + let (l, r) = m.split_at(n); + let mut output = [r, l].concat(); + let (mut r, mut l) = output.split_at_mut(n); + + let mut key = [&[0], p].concat(); + let mut salt = iter::empty() + .chain(*b"shamir") + .chain(id.to_be_bytes()) + .chain(iter::repeat(0).take(n)) + .collect::<Vec<_>>(); + let rounds = 2500 << e; + let mut buf = vec![0; n]; + + for i in instances { + key[0] = i; + salt[8..].copy_from_slice(r); + pbkdf2::pbkdf2::<Hmac<Sha256>>(&key, &salt, rounds, &mut buf) + .expect("HMAC can be initialized with any key length"); + for (l, b) in l.iter_mut().zip(&buf) { + *l ^= *b; + } + + (l, r) = (r, l); + } + + output +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn feistel_ecryption() { + let secret = b"hello shamir"; + let enc = encrypt(secret, b"password", 0, 0x1337); + let dec = decrypt(&enc, b"password", 0, 0x1337); + assert_eq!(secret[..], dec); + } +} |
