diff options
Diffstat (limited to 'src/shamir')
| -rw-r--r-- | src/shamir/cypher.rs | 60 | ||||
| -rw-r--r-- | src/shamir/secret.rs | 199 | ||||
| -rw-r--r-- | src/shamir/wordlist.rs | 62 | ||||
| -rw-r--r-- | src/shamir/wordlist.txt | 1024 |
4 files changed, 1306 insertions, 39 deletions
diff --git a/src/shamir/cypher.rs b/src/shamir/cypher.rs new file mode 100644 index 0000000..315495f --- /dev/null +++ b/src/shamir/cypher.rs @@ -0,0 +1,60 @@ +//! Implementation of SLIP-0039 secret encryption cypher. + +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); + } +} diff --git a/src/shamir/secret.rs b/src/shamir/secret.rs index d2e8887..db2c84f 100644 --- a/src/shamir/secret.rs +++ b/src/shamir/secret.rs @@ -1,49 +1,115 @@ -//! Implementation of SLIP-0039 secret encryption. +//! SLIP-0039 secret splitting and restoring. -use hmac::Hmac; +use super::ff; +use crate::rand; +use anyhow::{ensure, Result}; +use hmac::{Hmac, Mac as _}; 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]) -} +/// Lagrange interpolation of a polynomial at `x` described by the specified +/// points. +fn interpolate(ps: &[(u8, &[u8])], x: u8, y: &mut [u8]) { + assert_lengths(y.len(), ps.iter().map(|(_, yi)| *yi)); -/// 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]) + let ps = || ps.iter().copied().enumerate(); + for (i, (xi, yi)) in ps() { + let mut pi = 1; + 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 (yk, yik) in y.iter_mut().zip(yi) { + *yk = ff::add(*yk, ff::mul(*yik, pi)); + } + } } -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"); +/// Splits a secret into `n` shares, with a threshold recovery `t`. Returns a +/// `Vec` with `n` elements representing each of the shares. +pub fn split(t: usize, n: usize, s: &[u8]) -> Vec<Vec<u8>> { + let m = s.len(); + debug_assert!( + 0 < t && t <= n && n <= 16 && m >= 16 && m % 2 == 0, + "invalid shamir parameters", + ); + + if t == 1 { + return (0..n).map(|_| s.to_vec()).collect(); + } + + let d = { + let mut buf = vec![0; m]; + + let r = &mut buf[4..]; + rand::fill(r); + + let code = hmac_sha256(r, s); + buf[..4].copy_from_slice(&code[..4]); + + buf + }; - 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 ys = vec![vec![0; m]; n]; + let (ysr, ysi) = ys.split_at_mut(t - 2); - 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)) + for y in ysr.iter_mut() { + rand::fill(y.as_mut()); + } + + let ps = ysr + .iter() + .enumerate() + .map(|(x, y)| (x as u8, &y[..])) + .chain([(254, &d[..]), (255, s)]) .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; - } + for (i, y) in ysi.iter_mut().enumerate() { + let x = i + t - 2; + interpolate(&ps, x as _, y); + } - (l, r) = (r, l); + ys +} + +/// Recovers a secret from a list of shares for a threshold `t`. +pub fn recover(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 && m >= 16 && m % 2 == 0, + "invalid shamir parameters" + ); + + if t == 1 { + return Ok(ps[0].1.to_vec()); } - output + let (mut s, mut d) = (vec![0; m], vec![0; m]); + + interpolate(ps, 255, &mut s); + interpolate(ps, 254, &mut d); + + let r = &d[4..]; + let code = hmac_sha256(r, &s[..]); + + ensure!(d[..4] == code[..4], "secret checksum mismatch"); + Ok(s) +} + +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)] @@ -51,10 +117,65 @@ 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); + fn lagrange_interpolation() { + let mut y = [0, 0]; + interpolate(&[(1, &[118, 56]), (2, &[146, 14])], 0, &mut y); + + assert_eq!(y, [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(3, 5, &secret); + + // Insufficient shares + assert!(recover(&[(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 { + if i == j || i == k || j == k { + continue; + } + + let exact = recover(&[ + (i as _, &shares[i]), + (j as _, &shares[j]), + (k as _, &shares[k]), + ]) + .unwrap(); + assert_eq!(secret[..], exact); + } + } + } + + // Extra shares + let extra = recover(&[ + (0, &shares[0]), + (1, &shares[1]), + (2, &shares[2]), + (3, &shares[3]), + (4, &shares[4]), + ]) + .unwrap(); + assert_eq!(secret[..], extra); + } + + #[test] + fn very_large_secret() { + let secret = [42; 8192]; + let shares = split(2, 2, &secret); + let recovered = recover(&[(0, &shares[0]), (1, &shares[1])]).unwrap(); + + assert_eq!(&secret[..], recovered); } } diff --git a/src/shamir/wordlist.rs b/src/shamir/wordlist.rs new file mode 100644 index 0000000..16fe006 --- /dev/null +++ b/src/shamir/wordlist.rs @@ -0,0 +1,62 @@ +//! Module containing the embedded SLIP-0039 word list. + +use std::sync::OnceLock; + +/// A parsed word list. +pub struct Wordlist<'a>(Vec<&'a str>); + +/// The number of words in the list, as defined in SLIP-0039. +pub const WORD_COUNT: usize = 1024; +/// Masking value for a mnemonic word. +pub const WORD_MASK: usize = WORD_COUNT - 1; +/// The number of bits represented by each mnemonic word. +pub const WORD_BITS: usize = WORD_MASK.count_ones() as _; + +impl<'a> Wordlist<'a> { + /// Parses a list of newline-separated words. + fn parse(words: &'a str) -> Wordlist<'a> { + let words = words.trim().split('\n').map(str::trim).collect::<Vec<_>>(); + + debug_assert_eq!(words.len(), WORD_COUNT); + debug_assert!(words + .iter() + .all(|word| word.chars().all(char::is_lowercase))); + debug_assert!(words.windows(2).all(|pair| pair[0] < pair[1])); + + Wordlist(words) + } + + /// Searches the word list for the specified word returning its numerical + /// value representing its index in the list. This method returns `None` + /// if the word does not belong to the list. + pub fn search(&self, word: impl AsRef<str>) -> Option<usize> { + self.0.binary_search(&word.as_ref()).ok() + } + + /// Returns the word for the specified index. + /// + /// # Panics + /// + /// This method panics if the index is out of range for the SLIP-0039 word + /// list: it must be less than `WORD_COUNT` or `1024`. + pub fn word(&'a self, index: usize) -> &'a str { + assert!(index < WORD_COUNT, "invalid word index"); + self.0[index] + } +} + +/// Retrieves the SLIP-0039 word list. +pub fn wordlist() -> &'static Wordlist<'static> { + static WORDLIST: OnceLock<Wordlist> = OnceLock::new(); + WORDLIST.get_or_init(|| Wordlist::parse(include_str!("wordlist.txt"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_wordlist() { + wordlist(); + } +} diff --git a/src/shamir/wordlist.txt b/src/shamir/wordlist.txt new file mode 100644 index 0000000..5673e7c --- /dev/null +++ b/src/shamir/wordlist.txt @@ -0,0 +1,1024 @@ +academic +acid +acne +acquire +acrobat +activity +actress +adapt +adequate +adjust +admit +adorn +adult +advance +advocate +afraid +again +agency +agree +aide +aircraft +airline +airport +ajar +alarm +album +alcohol +alien +alive +alpha +already +alto +aluminum +always +amazing +ambition +amount +amuse +analysis +anatomy +ancestor +ancient +angel +angry +animal +answer +antenna +anxiety +apart +aquatic +arcade +arena +argue +armed +artist +artwork +aspect +auction +august +aunt +average +aviation +avoid +award +away +axis +axle +beam +beard +beaver +become +bedroom +behavior +being +believe +belong +benefit +best +beyond +bike +biology +birthday +bishop +black +blanket +blessing +blimp +blind +blue +body +bolt +boring +born +both +boundary +bracelet +branch +brave +breathe +briefing +broken +brother +browser +bucket +budget +building +bulb +bulge +bumpy +bundle +burden +burning +busy +buyer +cage +calcium +camera +campus +canyon +capacity +capital +capture +carbon +cards +careful +cargo +carpet +carve +category +cause +ceiling +center +ceramic +champion +change +charity +check +chemical +chest +chew +chubby +cinema +civil +class +clay +cleanup +client +climate +clinic +clock +clogs +closet +clothes +club +cluster +coal +coastal +coding +column +company +corner +costume +counter +course +cover +cowboy +cradle +craft +crazy +credit +cricket +criminal +crisis +critical +crowd +crucial +crunch +crush +crystal +cubic +cultural +curious +curly +custody +cylinder +daisy +damage +dance +darkness +database +daughter +deadline +deal +debris +debut +decent +decision +declare +decorate +decrease +deliver +demand +density +deny +depart +depend +depict +deploy +describe +desert +desire +desktop +destroy +detailed +detect +device +devote +diagnose +dictate +diet +dilemma +diminish +dining +diploma +disaster +discuss +disease +dish +dismiss +display +distance +dive +divorce +document +domain +domestic +dominant +dough +downtown +dragon +dramatic +dream +dress +drift +drink +drove +drug +dryer +duckling +duke +duration +dwarf +dynamic +early +earth +easel +easy +echo +eclipse +ecology +edge +editor +educate +either +elbow +elder +election +elegant +element +elephant +elevator +elite +else +email +emerald +emission +emperor +emphasis +employer +empty +ending +endless +endorse +enemy +energy +enforce +engage +enjoy +enlarge +entrance +envelope +envy +epidemic +episode +equation +equip +eraser +erode +escape +estate +estimate +evaluate +evening +evidence +evil +evoke +exact +example +exceed +exchange +exclude +excuse +execute +exercise +exhaust +exotic +expand +expect +explain +express +extend +extra +eyebrow +facility +fact +failure +faint +fake +false +family +famous +fancy +fangs +fantasy +fatal +fatigue +favorite +fawn +fiber +fiction +filter +finance +findings +finger +firefly +firm +fiscal +fishing +fitness +flame +flash +flavor +flea +flexible +flip +float +floral +fluff +focus +forbid +force +forecast +forget +formal +fortune +forward +founder +fraction +fragment +frequent +freshman +friar +fridge +friendly +frost +froth +frozen +fumes +funding +furl +fused +galaxy +game +garbage +garden +garlic +gasoline +gather +general +genius +genre +genuine +geology +gesture +glad +glance +glasses +glen +glimpse +goat +golden +graduate +grant +grasp +gravity +gray +greatest +grief +grill +grin +grocery +gross +group +grownup +grumpy +guard +guest +guilt +guitar +gums +hairy +hamster +hand +hanger +harvest +have +havoc +hawk +hazard +headset +health +hearing +heat +helpful +herald +herd +hesitate +hobo +holiday +holy +home +hormone +hospital +hour +huge +human +humidity +hunting +husband +hush +husky +hybrid +idea +identify +idle +image +impact +imply +improve +impulse +include +income +increase +index +indicate +industry +infant +inform +inherit +injury +inmate +insect +inside +install +intend +intimate +invasion +involve +iris +island +isolate +item +ivory +jacket +jerky +jewelry +join +judicial +juice +jump +junction +junior +junk +jury +justice +kernel +keyboard +kidney +kind +kitchen +knife +knit +laden +ladle +ladybug +lair +lamp +language +large +laser +laundry +lawsuit +leader +leaf +learn +leaves +lecture +legal +legend +legs +lend +length +level +liberty +library +license +lift +likely +lilac +lily +lips +liquid +listen +literary +living +lizard +loan +lobe +location +losing +loud +loyalty +luck +lunar +lunch +lungs +luxury +lying +lyrics +machine +magazine +maiden +mailman +main +makeup +making +mama +manager +mandate +mansion +manual +marathon +march +market +marvel +mason +material +math +maximum +mayor +meaning +medal +medical +member +memory +mental +merchant +merit +method +metric +midst +mild +military +mineral +minister +miracle +mixed +mixture +mobile +modern +modify +moisture +moment +morning +mortgage +mother +mountain +mouse +move +much +mule +multiple +muscle +museum +music +mustang +nail +national +necklace +negative +nervous +network +news +nuclear +numb +numerous +nylon +oasis +obesity +object +observe +obtain +ocean +often +olympic +omit +oral +orange +orbit +order +ordinary +organize +ounce +oven +overall +owner +paces +pacific +package +paid +painting +pajamas +pancake +pants +papa +paper +parcel +parking +party +patent +patrol +payment +payroll +peaceful +peanut +peasant +pecan +penalty +pencil +percent +perfect +permit +petition +phantom +pharmacy +photo +phrase +physics +pickup +picture +piece +pile +pink +pipeline +pistol +pitch +plains +plan +plastic +platform +playoff +pleasure +plot +plunge +practice +prayer +preach +predator +pregnant +premium +prepare +presence +prevent +priest +primary +priority +prisoner +privacy +prize +problem +process +profile +program +promise +prospect +provide +prune +public +pulse +pumps +punish +puny +pupal +purchase +purple +python +quantity +quarter +quick +quiet +race +racism +radar +railroad +rainbow +raisin +random +ranked +rapids +raspy +reaction +realize +rebound +rebuild +recall +receiver +recover +regret +regular +reject +relate +remember +remind +remove +render +repair +repeat +replace +require +rescue +research +resident +response +result +retailer +retreat +reunion +revenue +review +reward +rhyme +rhythm +rich +rival +river +robin +rocky +romantic +romp +roster +round +royal +ruin +ruler +rumor +sack +safari +salary +salon +salt +satisfy +satoshi +saver +says +scandal +scared +scatter +scene +scholar +science +scout +scramble +screw +script +scroll +seafood +season +secret +security +segment +senior +shadow +shaft +shame +shaped +sharp +shelter +sheriff +short +should +shrimp +sidewalk +silent +silver +similar +simple +single +sister +skin +skunk +slap +slavery +sled +slice +slim +slow +slush +smart +smear +smell +smirk +smith +smoking +smug +snake +snapshot +sniff +society +software +soldier +solution +soul +source +space +spark +speak +species +spelling +spend +spew +spider +spill +spine +spirit +spit +spray +sprinkle +square +squeeze +stadium +staff +standard +starting +station +stay +steady +step +stick +stilt +story +strategy +strike +style +subject +submit +sugar +suitable +sunlight +superior +surface +surprise +survive +sweater +swimming +swing +switch +symbolic +sympathy +syndrome +system +tackle +tactics +tadpole +talent +task +taste +taught +taxi +teacher +teammate +teaspoon +temple +tenant +tendency +tension +terminal +testify +texture +thank +that +theater +theory +therapy +thorn +threaten +thumb +thunder +ticket +tidy +timber +timely +ting +tofu +together +tolerate +total +toxic +tracks +traffic +training +transfer +trash +traveler +treat +trend +trial +tricycle +trip +triumph +trouble +true +trust +twice +twin +type +typical +ugly +ultimate +umbrella +uncover +undergo +unfair +unfold +unhappy +union +universe +unkind +unknown +unusual +unwrap +upgrade +upstairs +username +usher +usual +valid +valuable +vampire +vanish +various +vegan +velvet +venture +verdict +verify +very +veteran +vexed +victim +video +view +vintage +violence +viral +visitor +visual +vitamins +vocal +voice +volume +voter +voting +walnut +warmth +warn +watch +wavy +wealthy +weapon +webcam +welcome +welfare +western +width +wildlife +window +wine +wireless +wisdom +withdraw +wits +wolf +woman +work +worthy +wrap +wrist +writing +wrote +year +yelp +yield +yoga +zero |
