diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/lib.rs | 2 | ||||
| -rw-r--r-- | src/mnemonic.rs | 2 | ||||
| -rw-r--r-- | src/rand.rs | 38 | ||||
| -rw-r--r-- | src/shamir.rs | 158 | ||||
| -rw-r--r-- | src/shamir/ff.rs | 23 |
5 files changed, 202 insertions, 21 deletions
@@ -10,9 +10,9 @@ pub mod message; pub mod mnemonic; mod rand; mod serialization; +pub mod shamir; pub mod transaction; pub mod typeddata; -pub mod shamir; #[cfg(test)] mod ganache; diff --git a/src/mnemonic.rs b/src/mnemonic.rs index a9420c4..2cf04bb 100644 --- a/src/mnemonic.rs +++ b/src/mnemonic.rs @@ -47,7 +47,7 @@ impl Mnemonic { let mut buf = [0; 64]; let (seed, hash) = buf.split_at_mut(len); - rand::get_entropy(&mut *seed)?; + rand::fill(&mut *seed); hash_seed(seed, hash); buf diff --git a/src/rand.rs b/src/rand.rs index e1e74b5..ce5f2df 100644 --- a/src/rand.rs +++ b/src/rand.rs @@ -1,11 +1,22 @@ //! Cryptographically secure randomness. -use std::{io, os::raw::c_int}; +use std::io; -/// Populates the provided slice with cryptographically strong entropy. -pub fn get_entropy(mut buf: impl AsMut<[u8]>) -> io::Result<()> { - let buf = buf.as_mut(); - let result = unsafe { getentropy(buf.as_mut_ptr(), buf.len()) }; +/// The maximum amount of entropy that can be read at a time. +pub const MAX_SIZE: usize = 256; + +/// Fills the specified slice with cryptographically strong entropy. +pub fn fill(buf: &mut [u8]) { + for chunk in buf.chunks_mut(MAX_SIZE) { + getentropy(chunk).expect("chunk size less than max"); + } +} + +/// Populates the specified slice with cryptographically strong entropy. +/// +/// Returns an error if the buffer length is greater than [`MAX_SIZE`]. +pub fn getentropy(buf: &mut [u8]) -> io::Result<()> { + let result = unsafe { ffi::getentropy(buf.as_mut_ptr(), buf.len()) }; if result >= 0 { Ok(()) } else { @@ -13,8 +24,12 @@ pub fn get_entropy(mut buf: impl AsMut<[u8]>) -> io::Result<()> { } } -extern "C" { - fn getentropy(buffer: *mut u8, len: usize) -> c_int; +mod ffi { + use std::ffi::c_int; + + extern "C" { + pub fn getentropy(buffer: *mut u8, len: usize) -> c_int; + } } #[cfg(test)] @@ -24,13 +39,14 @@ mod tests { #[test] fn read_os_entropy() { let mut buf = [0u8; 32]; - assert!(get_entropy(&mut buf[..16]).is_ok()); - assert!(get_entropy(&mut buf).is_ok()); + assert!(getentropy(&mut buf[..16]).is_ok()); + assert!(getentropy(&mut buf).is_ok()); } #[test] fn error_reading_more_than_256_bytes() { - let mut buf = [0u8; 257]; - assert!(get_entropy(&mut buf).is_err()); + let mut buf = [0u8; MAX_SIZE + 1]; + assert!(getentropy(&mut buf[..MAX_SIZE]).is_ok()); + assert!(getentropy(&mut buf).is_err()); } } diff --git a/src/shamir.rs b/src/shamir.rs index ba3e043..64be065 100644 --- a/src/shamir.rs +++ b/src/shamir.rs @@ -3,9 +3,165 @@ //! This implementation follows the SLIP-0039 standard for generating and //! encoding shares with mnemonics. +use crate::rand; +use anyhow::{ensure, Result}; +use hmac::{Hmac, Mac as _}; +use sha2::Sha256; + mod ff; /// A single share for a secret. -pub struct Share { +pub struct Share {} + +/// 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(); + + let mut y = [0; N]; + for (xi, yi) in points() { + let mut pi = 1; + for (xj, _) in points().filter(|(xj, _)| *xj != xi) { + 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)); + } + } + 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]> { + debug_assert!( + 0 < t && t <= n && n <= 16 && N >= 16 && N <= 36, + "invalid shamir parameters", + ); + + if t == 1 { + return (0..n).map(|_| *s).collect(); + } + + let d = { + let mut buf = [0; N]; + + 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(); + buf[..4].copy_from_slice(&code[..4]); + + buf + }; + + let mut ys = vec![[0; N]; n]; + let (ysr, ysi) = ys.split_at_mut(t - 2); + + for y in ysr.iter_mut() { + rand::getentropy(y).expect("y is small enough"); + } + + let points = ysr + .iter() + .enumerate() + .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) + } + + 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]> { + debug_assert!( + 0 < t && t <= 16 && t <= ps.len() && N >= 16 && N <= 36, + "invalid shamir parameters", + ); + + if t == 1 { + return Ok(*ps[0].1); + } + + let s = interpolate(255, ps); + let d = interpolate(254, ps); + + 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() + }; + + ensure!(d[..4] == code[..4], "secret checksum mismatch"); + + Ok(s) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lagrange_interpolation() { + assert_eq!( + interpolate(0, &[(1, &[118, 56]), (2, &[146, 14])]), + [42, 42] + ); + } + + #[test] + fn split_and_recover() { + let secret = { + let mut buf = [0; 32]; + for (i, b) in buf.iter_mut().enumerate() { + *b = (i + 1) as u8; + } + buf + }; + + let shares = split_secret(3, 5, &secret); + for i in 0..5 { + for j in 0..5 { + for k in 0..5 { + if i == j || i == k || j == k { + continue; + } + + let recovered = recover_secret( + 3, + &[ + (i as _, &shares[i]), + (j as _, &shares[j]), + (k as _, &shares[k]), + ], + ) + .unwrap(); + assert_eq!(secret, recovered); + } + } + } + + let extra = recover_secret( + 3, + &[ + (0, &shares[0]), + (1, &shares[1]), + (2, &shares[2]), + (3, &shares[3]), + (4, &shares[4]), + ], + ) + .unwrap(); + assert_eq!(secret, extra); + let missing = interpolate(255, &[(0, &shares[0]), (1, &shares[1])]); + assert_ne!(secret, missing); + } } diff --git a/src/shamir/ff.rs b/src/shamir/ff.rs index d384f34..afef462 100644 --- a/src/shamir/ff.rs +++ b/src/shamir/ff.rs @@ -9,21 +9,30 @@ pub fn add(a: u8, b: u8) -> u8 { } /// Subtracts two elements of GF(256). Constant time. -pub use add as sub; +pub fn sub(a: u8, b: u8) -> u8 { + add(a, b) +} /// Multiplies two elements of GF(256). Constant time. pub fn mul(mut a: u8, mut b: u8) -> u8 { + /// `0xff` if LSB is set, `0` otherwise. + #[inline(always)] + fn lsb(x: u8) -> u8 { + -((x & 1) as i8) as _ + } + + /// `0xff` if MSB is set, `0` otherwise. #[inline(always)] - fn neg(x: u8) -> u8 { - -(x as i8) as _ + fn msb(x: u8) -> u8 { + ((x as i8) >> 7) as _ } let mut p = 0; macro_rules! it { () => { - p = add(p, neg(b & 1) & a); - a = sub(a << 1, neg(a >> 7) & (P as u8)); + p = add(p, lsb(b) & a); + a = sub(a << 1, msb(a) & (P as u8)); b >>= 1; }; } @@ -35,7 +44,7 @@ pub fn mul(mut a: u8, mut b: u8) -> u8 { it!(); it!(); - add(p, neg(b & 1) & a) + add(p, lsb(b) & a) } /// Divides two elements of GF(256). Constant time. @@ -45,7 +54,7 @@ pub fn div(a: u8, b: u8) -> u8 { #[inline(always)] fn inv(x: u8) -> u8 { // This is fun... but the inverse of b, is just b to the power of 254. - let mut i = x; + let mut i = x; // x^1 i = mul(i, i); // x^2 i = mul(i, x); // x^3 i = mul(i, i); // x^6 |
