├── .gitignore ├── .travis.yml ├── LICENSE ├── src ├── lib.rs ├── fields │ ├── native.rs │ ├── montgomery.rs │ ├── mod.rs │ └── fft.rs ├── shamir.rs ├── numtheory.rs └── packed.rs ├── Cargo.toml ├── LICENSE-MIT ├── examples ├── shamir.rs └── homomorphic.rs ├── benches └── packed.rs ├── README.md └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | *.rs.bk 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta 5 | - nightly 6 | matrix: 7 | allow_failures: 8 | - rust: nightly 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | ## License 2 | 3 | Licensed under either of 4 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 5 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 6 | at your option. 7 | 8 | ### Contribution 9 | 10 | Unless you explicitly state otherwise, any contribution intentionally submitted 11 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall 12 | be dual licensed as above, without any additional terms or conditions. 13 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 rust-threshold-secret-sharing developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 4 | // or the MIT 5 | // license , at your 6 | // option. All files in the project carrying such notice may not be copied, 7 | // modified, or distributed except according to those terms. 8 | 9 | //! # Threshold Secret Sharing 10 | //! Pure-Rust library for [secret sharing](https://en.wikipedia.org/wiki/Secret_sharing), 11 | //! offering efficient share generation and reconstruction for both 12 | //! traditional Shamir sharing and its packet (or ramp) variant. 13 | //! For now, secrets and shares are fixed as prime field elements 14 | //! represented by `i64` values. 15 | 16 | extern crate rand; 17 | 18 | mod fields; 19 | mod numtheory; 20 | pub use numtheory::positivise; 21 | 22 | pub mod shamir; 23 | pub mod packed; 24 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "threshold-secret-sharing" 3 | version = "0.2.3-pre" 4 | authors = [ 5 | "Morten Dahl ", 6 | "Mathieu Poumeyrol " 7 | ] 8 | description = "A pure-Rust implementation of various threshold secret sharing schemes" 9 | keywords = [ 10 | "secret-sharing", 11 | "Shamir", 12 | "cryptography", 13 | "secure-computation", 14 | "mpc" 15 | ] 16 | homepage = "https://github.com/snipsco/rust-threshold-secret-sharing" 17 | documentation = "https://docs.rs/threshold-secret-sharing" 18 | license = "MIT/Apache-2.0" 19 | categories = [ "cryptography" ] 20 | 21 | [badges] 22 | travis-ci = { repository = "snipsco/rust-threshold-secret-sharing" } 23 | 24 | [features] 25 | paramgen = ["primal"] 26 | 27 | [dependencies] 28 | rand = "0.3.*" 29 | primal = { version = "0.2", optional = true } 30 | 31 | [dev-dependencies] 32 | bencher = "0.1" 33 | 34 | [[bench]] 35 | name = "packed" 36 | harness = false 37 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /examples/shamir.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 rust-threshold-secret-sharing developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 4 | // or the MIT 5 | // license , at your 6 | // option. All files in the project carrying such notice may not be copied, 7 | // modified, or distributed except according to those terms. 8 | extern crate threshold_secret_sharing as tss; 9 | 10 | fn main() { 11 | 12 | let ref tss = tss::shamir::ShamirSecretSharing { 13 | threshold: 9, 14 | share_count: 20, 15 | prime: 41 // any large enough prime will do 16 | }; 17 | 18 | let secret = 5; 19 | let all_shares = tss.share(secret); 20 | 21 | let reconstruct_share_count = 10; 22 | assert!(reconstruct_share_count >= tss.reconstruct_limit()); 23 | 24 | let indices: Vec = (0..reconstruct_share_count).collect(); 25 | let shares: &[i64] = &all_shares[0..reconstruct_share_count]; 26 | let recovered_secret = tss.reconstruct(&indices, shares); 27 | 28 | println!("The recovered secret is {}", recovered_secret); 29 | assert_eq!(recovered_secret, secret); 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/fields/native.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 rust-threshold-secret-sharing developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 4 | // or the MIT 5 | // license , at your 6 | // option. All files in the project carrying such notice may not be copied, 7 | // modified, or distributed except according to those terms. 8 | 9 | //! Trivial native modular field. 10 | 11 | use super::Field; 12 | 13 | 14 | #[derive(Copy,Clone,Debug)] 15 | pub struct Value(i64); 16 | 17 | /// Trivial implementaion of Field using i64 values and performing a native 18 | /// modulo reduction after each operation. 19 | /// 20 | /// Actual values show not exceed the u32 or i32 ranges as multiplication 21 | /// are performed "naively". 22 | /// 23 | /// The mais purpose of this struct is to serve as a test reference to the 24 | /// more challenging implementations. 25 | pub struct NativeField(i64); 26 | 27 | impl Field for NativeField { 28 | type U = Value; 29 | 30 | fn new(prime: u64) -> NativeField { 31 | NativeField(prime as i64) 32 | } 33 | 34 | fn modulus(&self) -> u64 { 35 | self.0 as u64 36 | } 37 | 38 | fn from_u64(&self, a: u64) -> Self::U { 39 | Value(a as i64 % self.0) 40 | } 41 | 42 | fn to_u64(&self, a: Self::U) -> u64 { 43 | a.0 as u64 44 | } 45 | 46 | fn add(&self, a: Self::U, b: Self::U) -> Self::U { 47 | Value((a.0 + b.0) % self.0) 48 | } 49 | 50 | fn sub(&self, a: Self::U, b: Self::U) -> Self::U { 51 | let tmp = a.0 - b.0; 52 | if tmp > 0 { 53 | Value(tmp) 54 | } else { 55 | Value(tmp + self.0) 56 | } 57 | } 58 | 59 | fn mul(&self, a: Self::U, b: Self::U) -> Self::U { 60 | Value((a.0 * b.0) % self.0) 61 | } 62 | 63 | fn inv(&self, a: Self::U) -> Self::U { 64 | let tmp = ::numtheory::mod_inverse((a.0 % self.0) as i64, self.0 as i64); 65 | self.from_i64(tmp) 66 | } 67 | } 68 | 69 | #[cfg(test)] 70 | all_fields_test!(NativeField); 71 | -------------------------------------------------------------------------------- /benches/packed.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 rust-threshold-secret-sharing developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 4 | // or the MIT 5 | // license , at your 6 | // option. All files in the project carrying such notice may not be copied, 7 | // modified, or distributed except according to those terms. 8 | 9 | #[macro_use] 10 | extern crate bencher; 11 | extern crate threshold_secret_sharing as tss; 12 | 13 | mod shamir_vs_packed { 14 | 15 | use bencher::Bencher; 16 | use tss::shamir::*; 17 | 18 | pub fn bench_100_shamir(b: &mut Bencher) { 19 | let ref tss = ShamirSecretSharing { 20 | threshold: 155 / 3, 21 | parts: 728 / 3, 22 | prime: 746497, 23 | }; 24 | 25 | let all_secrets: Vec = vec![5 ; 100 ]; 26 | b.iter(|| { 27 | let _shares: Vec> = all_secrets.iter() 28 | .map(|&secret| tss.share(secret)) 29 | .collect(); 30 | }); 31 | } 32 | 33 | pub fn bench_100_packed(b: &mut Bencher) { 34 | use tss::packed::*; 35 | let ref pss = PSS_155_728_100; 36 | let all_secrets: Vec = vec![5 ; 100]; 37 | b.iter(|| { 38 | let _shares = pss.share(&all_secrets); 39 | }) 40 | } 41 | 42 | } 43 | 44 | benchmark_group!(shamir_vs_packed, 45 | shamir_vs_packed::bench_100_shamir, 46 | shamir_vs_packed::bench_100_packed); 47 | 48 | 49 | mod packed { 50 | 51 | use bencher::Bencher; 52 | use tss::packed::*; 53 | 54 | pub fn bench_large_secret_count(b: &mut Bencher) { 55 | let ref pss = PSS_155_728_100; 56 | let all_secrets = vec![5 ; pss.secret_count * 100]; 57 | b.iter(|| { 58 | let _shares: Vec> = all_secrets.chunks(pss.secret_count) 59 | .map(|secrets| pss.share(&secrets)) 60 | .collect(); 61 | }); 62 | } 63 | 64 | pub fn bench_large_share_count(b: &mut Bencher) { 65 | let ref pss = PSS_155_19682_100; 66 | let secrets = vec![5 ; pss.secret_count]; 67 | b.iter(|| { 68 | let _shares = pss.share(&secrets); 69 | }); 70 | } 71 | 72 | pub fn bench_large_reconstruct(b: &mut Bencher) { 73 | let ref pss = PSS_155_19682_100; 74 | let secrets = vec![5 ; pss.secret_count]; 75 | let all_shares = pss.share(&secrets); 76 | 77 | // reconstruct using minimum number of shares required 78 | let indices: Vec = (0..pss.reconstruct_limit()).collect(); 79 | let shares = &all_shares[0..pss.reconstruct_limit()]; 80 | 81 | b.iter(|| { 82 | let _recovered_secrets = pss.reconstruct(&indices, &shares); 83 | }); 84 | } 85 | 86 | } 87 | 88 | benchmark_group!(packed, 89 | packed::bench_large_secret_count, 90 | packed::bench_large_share_count, 91 | packed::bench_large_reconstruct); 92 | 93 | benchmark_main!(shamir_vs_packed, packed); 94 | -------------------------------------------------------------------------------- /src/fields/montgomery.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 rust-threshold-secret-sharing developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 4 | // or the MIT 5 | // license , at your 6 | // option. All files in the project carrying such notice may not be copied, 7 | // modified, or distributed except according to those terms. 8 | 9 | //! Montgomery modular multiplication field. 10 | 11 | use super::Field; 12 | 13 | /// MontgomeryField32 Value (wraps an u32 for type-safety). 14 | #[derive(Copy,Clone,Debug)] 15 | pub struct Value(u32); 16 | 17 | /// Implementation of Field with Montgomery modular multiplication. 18 | /// 19 | /// See https://en.wikipedia.org/wiki/Montgomery_modular_multiplication 20 | /// for general description of the scheme, or 21 | /// http://www.hackersdelight.org/MontgomeryMultiplication.pdf for 22 | /// implementation notes. 23 | /// 24 | /// This implementation assumes R=2^32. In other terms, the modulus must be 25 | /// in the u32 range. All values will be positive, in the 0..modulus range, 26 | /// and represented by a u32. 27 | pub struct MontgomeryField32 { 28 | pub n: u32, // the prime 29 | pub n_quote: u32, 30 | pub r_inv: u32, // r = 2^32 31 | pub r_cube: u32, // r^3 is used by inv() 32 | } 33 | 34 | impl MontgomeryField32 { 35 | pub fn new(prime: u32) -> MontgomeryField32 { 36 | let r = 1u64 << 32; 37 | let tmp = ::numtheory::mod_inverse(r as i64, prime as i64); 38 | let r_inv = if tmp < 0 { 39 | (tmp + prime as i64) as u32 40 | } else { 41 | tmp as u32 42 | }; 43 | let tmp = ::numtheory::mod_inverse(prime as i64, r as i64); 44 | let n_quote = if tmp > 0 { 45 | (r as i64 - tmp) as u32 46 | } else { 47 | (r as i64 - tmp) as u32 48 | }; 49 | let r_cube = ::numtheory::mod_pow(r as i64 % prime as i64, 3u32, prime as i64); 50 | MontgomeryField32 { 51 | n: prime, 52 | r_inv: r_inv, 53 | n_quote: n_quote, 54 | r_cube: r_cube as u32, 55 | } 56 | } 57 | 58 | fn redc(&self, a: u64) -> Value { 59 | let m: u64 = (a as u32).wrapping_mul(self.n_quote) as u64; 60 | let t: u32 = ((a + m * (self.n as u64)) >> 32) as u32; 61 | Value((if t >= (self.n) { t - (self.n) } else { t })) 62 | } 63 | } 64 | 65 | impl Field for MontgomeryField32 { 66 | type U = Value; 67 | 68 | fn modulus(&self) -> u64 { 69 | self.n as u64 70 | } 71 | 72 | fn add(&self, a: Self::U, b: Self::U) -> Self::U { 73 | let sum = a.0 as u64 + b.0 as u64; 74 | if sum > self.n as u64 { 75 | Value((sum - self.n as u64) as u32) 76 | } else { 77 | Value(sum as u32) 78 | } 79 | } 80 | 81 | fn sub(&self, a: Self::U, b: Self::U) -> Self::U { 82 | if a.0 > b.0 { 83 | Value(a.0 - b.0) 84 | } else { 85 | Value((a.0 as u64 + self.n as u64 - b.0 as u64) as u32) 86 | } 87 | } 88 | 89 | fn mul(&self, a: Self::U, b: Self::U) -> Self::U { 90 | self.redc((a.0 as u64).wrapping_mul(b.0 as u64)) 91 | } 92 | 93 | fn inv(&self, a: Self::U) -> Self::U { 94 | let ar_modn_inv = ::numtheory::mod_inverse(a.0 as i64, self.n as i64); 95 | self.redc((ar_modn_inv as u64).wrapping_mul(self.r_cube as u64)) 96 | } 97 | 98 | fn new(prime: u64) -> MontgomeryField32 { 99 | MontgomeryField32::new(prime as u32) 100 | } 101 | 102 | fn from_u64(&self, a: u64) -> Self::U { 103 | Value(((a << 32) % self.n as u64) as u32) 104 | } 105 | 106 | fn to_u64(&self, a: Self::U) -> u64 { 107 | a.0 as u64 * self.r_inv as u64 % self.n as u64 108 | } 109 | } 110 | 111 | #[cfg(test)] 112 | all_fields_test!(MontgomeryField32); 113 | -------------------------------------------------------------------------------- /examples/homomorphic.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 rust-threshold-secret-sharing developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 4 | // or the MIT 5 | // license , at your 6 | // option. All files in the project carrying such notice may not be copied, 7 | // modified, or distributed except according to those terms. 8 | extern crate threshold_secret_sharing as tss; 9 | 10 | fn main() { 11 | 12 | let ref pss = tss::packed::PSS_4_26_3; 13 | println!("\ 14 | Using parameters that: \n \ 15 | - allow {} values to be packed together \n \ 16 | - give a security threshold of {} \n \ 17 | - require {} of the {} shares to reconstruct in the basic case", 18 | pss.secret_count, 19 | pss.threshold, 20 | pss.reconstruct_limit(), 21 | pss.share_count 22 | ); 23 | 24 | // define inputs 25 | let secrets_1 = vec![1, 2, 3]; 26 | println!("\nFirst input vector: {:?}", &secrets_1); 27 | let secrets_2 = vec![4, 5, 6]; 28 | println!("Second input vector: {:?}", &secrets_2); 29 | let secrets_3 = vec![3, 2, 1]; 30 | println!("Third input vector: {:?}", &secrets_3); 31 | let secrets_4 = vec![6, 5, 4]; 32 | println!("Fourth input vector: {:?}", &secrets_4); 33 | 34 | // secret share inputs 35 | let shares_1 = pss.share(&secrets_1); 36 | println!("\nSharing of first vector gives random shares S1:\n{:?}", &shares_1); 37 | let shares_2 = pss.share(&secrets_2); 38 | println!("\nSharing of second vector gives random shares S2:\n{:?}", &shares_2); 39 | let shares_3 = pss.share(&secrets_3); 40 | println!("\nSharing of third vector gives random shares S3:\n{:?}", &shares_3); 41 | let shares_4 = pss.share(&secrets_4); 42 | println!("\nSharing of fourth vector gives random shares S4:\n{:?}", &shares_4); 43 | 44 | // in the following, 'positivise' is used to map (potentially negative) 45 | // values to their equivalent positive representation in Z_p for usability 46 | use tss::positivise; 47 | 48 | // multiply shares_1 and shares_2 point-wise 49 | let shares_12: Vec = shares_1.iter().zip(&shares_2).map(|(a, b)| (a * b) % pss.prime).collect(); 50 | // ... and reconstruct product, using double reconstruction limit 51 | let shares_12_reconstruct_limit = pss.reconstruct_limit() * 2; 52 | let foo: Vec = (0..shares_12_reconstruct_limit).collect(); 53 | let bar = &shares_12[0..shares_12_reconstruct_limit]; 54 | let secrets_12 = pss.reconstruct(&foo, bar); 55 | println!( 56 | "\nMultiplying shares S1 and S2 point-wise gives new shares S12 which \ 57 | can be reconstructed (using {} of them) to give output vector: {:?}", 58 | shares_12_reconstruct_limit, 59 | positivise(&secrets_12, pss.prime) 60 | ); 61 | 62 | // multiply shares_3 and shares_4 point-wise 63 | let shares_34: Vec = shares_3.iter().zip(&shares_4).map(|(a, b)| (a * b) % pss.prime).collect(); 64 | // ... and reconstruct product, using double reconstruction limit 65 | let shares_34_reconstruct_limit = pss.reconstruct_limit() * 2; 66 | let foo: Vec = (0..shares_34_reconstruct_limit).collect(); 67 | let bar = &shares_34[0..shares_34_reconstruct_limit]; 68 | let secrets_34 = pss.reconstruct(&foo, bar); 69 | println!( 70 | "\nLikewise, multiplying shares S3 and S4 point-wise gives new shares S34 \ 71 | which can be reconstructed (using {} of them) to give output vector: {:?}", 72 | shares_34_reconstruct_limit, 73 | positivise(&secrets_34, pss.prime) 74 | ); 75 | 76 | // multiply shares_sum12 and shares_34 point-wise 77 | let shares_1234product: Vec = shares_12.iter().zip(&shares_34).map(|(a, b)| (a * b) % pss.prime).collect(); 78 | // ... and reconstruct product, using double reconstruction limit 79 | let shares_1234product_reconstruct_limit = shares_1234product.len(); 80 | let foo: Vec = (0..shares_1234product_reconstruct_limit).collect(); 81 | let bar = &shares_1234product[0..shares_1234product_reconstruct_limit]; 82 | let secrets_1234product = pss.reconstruct(&foo, bar); 83 | println!( 84 | "\nIf we continue multiplying these new shares S12 and S34 then we no longer \ 85 | have enough shares to reconstruct correctly; using all {} shares gives incorrect (random) \ 86 | output: {:?}", 87 | shares_1234product_reconstruct_limit, 88 | positivise(&secrets_1234product, pss.prime) 89 | ); 90 | 91 | // add shares_12 and shares_34 point-wise 92 | let shares_1234sum: Vec = shares_12.iter().zip(&shares_34).map(|(a, b)| (a + b) % pss.prime).collect(); 93 | // ... and reconstruct sum, using same reconstruction limit as inputs 94 | let shares_1234sum_reconstruct_limit = pss.reconstruct_limit() * 2; 95 | let foo: Vec = (0..shares_1234sum_reconstruct_limit).collect(); 96 | let bar = &shares_1234sum[0..shares_1234sum_reconstruct_limit]; 97 | let secrets_1234sum = pss.reconstruct(&foo, bar); 98 | println!( 99 | "\nHowever, adding shares S12 and S34 point-wise doesn't increase the \ 100 | reconstruction limit and hence using {} shares we can still recover their sum: {:?}", 101 | shares_1234sum_reconstruct_limit, 102 | positivise(&secrets_1234sum, pss.prime) 103 | ); 104 | 105 | } 106 | -------------------------------------------------------------------------------- /src/fields/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 rust-threshold-secret-sharing developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 4 | // or the MIT 5 | // license , at your 6 | // option. All files in the project carrying such notice may not be copied, 7 | // modified, or distributed except according to those terms. 8 | 9 | //! This module implements in-place 2-radix and 3-radix numeric theory 10 | //! transformations (FFT on modular fields). 11 | 12 | pub mod fft; 13 | 14 | /// Abstract Field definition. 15 | /// 16 | /// This trait is not meant to represent a general field in the strict 17 | /// mathematical sense but it has everything we need to make the FFT to work. 18 | pub trait Field { 19 | type U: Copy; 20 | 21 | /// Create a modular field for the given prime. 22 | /// 23 | /// In the current state of implementation, only values in the u32 range 24 | /// should be used. 25 | fn new(prime: u64) -> Self; 26 | 27 | /// Get the modulus. 28 | fn modulus(&self) -> u64; 29 | 30 | /// Convert a u64 to a modular integer. 31 | fn from_u64(&self, a: u64) -> Self::U; 32 | 33 | /// Convert a modular integer to u64 in the 0..modulus range. 34 | fn to_u64(&self, a: Self::U) -> u64; 35 | 36 | /// Convert a i64 to a modular integer. 37 | fn from_i64(&self, a: i64) -> Self::U { 38 | let a = a % self.modulus() as i64; 39 | if a >= 0 { 40 | self.from_u64(a as u64) 41 | } else { 42 | self.from_u64((a + self.modulus() as i64) as u64) 43 | } 44 | } 45 | 46 | /// Convert a modular integer to i64 in the -modulus/2..+modulus/2 range. 47 | fn to_i64(&self, a: Self::U) -> i64 { 48 | let a = self.to_u64(a); 49 | if a > self.modulus() / 2 { 50 | a as i64 - self.modulus() as i64 51 | } else { 52 | a as i64 53 | } 54 | } 55 | 56 | /// Get the Zero value. 57 | fn zero(&self) -> Self::U { 58 | self.from_u64(0) 59 | } 60 | 61 | /// Get the One value. 62 | fn one(&self) -> Self::U { 63 | self.from_u64(1) 64 | } 65 | 66 | /// Perfoms a modular addition. 67 | fn add(&self, a: Self::U, b: Self::U) -> Self::U; 68 | 69 | /// Perfoms a modular substraction. 70 | fn sub(&self, a: Self::U, b: Self::U) -> Self::U; 71 | 72 | /// Perfoms a modular multiplication. 73 | fn mul(&self, a: Self::U, b: Self::U) -> Self::U; 74 | 75 | /// Perfoms a modular inverse. 76 | fn inv(&self, a: Self::U) -> Self::U; 77 | 78 | /// Perfoms a modular exponentiation (x^e % modulus). 79 | /// 80 | /// Implements exponentiation by squaring. 81 | fn qpow(&self, mut x: Self::U, mut e: u32) -> Self::U { 82 | let mut acc = self.one(); 83 | while e > 0 { 84 | if e % 2 == 0 { 85 | // even 86 | // no-op 87 | } else { 88 | // odd 89 | acc = self.mul(acc, x); 90 | } 91 | x = self.mul(x, x); // waste one of these by having it here but code is simpler (tiny bit) 92 | e = e >> 1; 93 | } 94 | acc 95 | } 96 | } 97 | 98 | macro_rules! all_fields_test { 99 | ($field:ty) => { 100 | #[test] fn test_convert() { ::fields::test::test_convert::<$field>(); } 101 | #[test] fn test_add() { ::fields::test::test_add::<$field>(); } 102 | #[test] fn test_sub() { ::fields::test::test_sub::<$field>(); } 103 | #[test] fn test_mul() { ::fields::test::test_mul::<$field>(); } 104 | #[test] fn test_qpow() { ::fields::test::test_qpow::<$field>(); } 105 | #[test] fn test_fft2() { ::fields::fft::test::test_fft2::<$field>(); } 106 | #[test] fn test_fft2_inverse() { ::fields::fft::test::test_fft2_inverse::<$field>(); } 107 | #[test] fn test_fft2_big() { ::fields::fft::test::test_fft2_big::<$field>(); } 108 | #[test] fn test_fft3() { ::fields::fft::test::test_fft3::<$field>(); } 109 | #[test] fn test_fft3_inverse() { ::fields::fft::test::test_fft3_inverse::<$field>(); } 110 | #[test] fn test_fft3_big() { ::fields::fft::test::test_fft3_big::<$field>(); } 111 | } 112 | } 113 | 114 | pub mod native; 115 | pub mod montgomery; 116 | 117 | #[cfg(test)] 118 | pub mod test { 119 | use super::Field; 120 | 121 | pub fn test_convert() { 122 | let zp = F::new(17); 123 | for i in 0u64..20 { 124 | assert_eq!(zp.to_u64(zp.from_u64(i)), i % 17); 125 | } 126 | } 127 | 128 | pub fn test_add() { 129 | let zp = F::new(17); 130 | assert_eq!(zp.to_u64(zp.add(zp.from_u64(8), zp.from_u64(2))), 10); 131 | assert_eq!(zp.to_u64(zp.add(zp.from_u64(8), zp.from_u64(13))), 4); 132 | } 133 | 134 | pub fn test_sub() { 135 | let zp = F::new(17); 136 | assert_eq!(zp.to_u64(zp.sub(zp.from_u64(8), zp.from_u64(2))), 6); 137 | assert_eq!(zp.to_u64(zp.sub(zp.from_u64(8), zp.from_u64(13))), 138 | (17 + 8 - 13) % 17); 139 | } 140 | 141 | pub fn test_mul() { 142 | let zp = F::new(17); 143 | assert_eq!(zp.to_u64(zp.mul(zp.from_u64(8), zp.from_u64(2))), 144 | (8 * 2) % 17); 145 | assert_eq!(zp.to_u64(zp.mul(zp.from_u64(8), zp.from_u64(5))), 146 | (8 * 5) % 17); 147 | } 148 | 149 | pub fn test_qpow() { 150 | let zp = F::new(17); 151 | assert_eq!(zp.to_u64(zp.qpow(zp.from_u64(2), 0)), 1); 152 | assert_eq!(zp.to_u64(zp.qpow(zp.from_u64(2), 3)), 8); 153 | assert_eq!(zp.to_u64(zp.qpow(zp.from_u64(2), 6)), 13); 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /src/shamir.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 rust-threshold-secret-sharing developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 4 | // or the MIT 5 | // license , at your 6 | // option. All files in the project carrying such notice may not be copied, 7 | // modified, or distributed except according to those terms. 8 | 9 | //! Standard [Shamir secret sharing](https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing) 10 | //! for a single secret. 11 | 12 | use rand; 13 | use numtheory::*; 14 | 15 | /// Parameters for the Shamir scheme, specifying privacy threshold and total number of shares. 16 | /// 17 | /// There are very few constraints except for the obvious ones: 18 | /// 19 | /// * `prime` must be a prime large enough to hold the secrets we plan to share 20 | /// * `share_count` must be at least `threshold + 1` (the reconstruction limit) 21 | /// 22 | /// # Example: 23 | /// 24 | /// ``` 25 | /// use threshold_secret_sharing::shamir; 26 | /// let tss = shamir::ShamirSecretSharing { 27 | /// threshold: 9, 28 | /// share_count: 20, 29 | /// prime: 41 30 | /// }; 31 | /// 32 | /// let secret = 5; 33 | /// let all_shares = tss.share(secret); 34 | /// 35 | /// let reconstruct_share_count = tss.reconstruct_limit(); 36 | /// 37 | /// let indices: Vec = (0..reconstruct_share_count).collect(); 38 | /// let shares: &[i64] = &all_shares[0..reconstruct_share_count]; 39 | /// let recovered_secret = tss.reconstruct(&indices, shares); 40 | /// 41 | /// println!("The recovered secret is {}", recovered_secret); 42 | /// assert_eq!(recovered_secret, secret); 43 | /// ``` 44 | #[derive(Debug)] 45 | pub struct ShamirSecretSharing { 46 | /// Maximum number of shares that can be known without exposing the secret. 47 | pub threshold: usize, 48 | /// Number of shares to split the secret into. 49 | pub share_count: usize, 50 | /// Prime defining the Zp field in which computation is taking place. 51 | pub prime: i64, 52 | } 53 | 54 | /// Small preset parameters for tests. 55 | pub static SHAMIR_5_20: ShamirSecretSharing = ShamirSecretSharing { 56 | threshold: 5, 57 | share_count: 20, 58 | prime: 41, 59 | }; 60 | 61 | impl ShamirSecretSharing { 62 | /// Minimum number of shares required to reconstruct secret. 63 | /// 64 | /// For this scheme this is always `threshold + 1`. 65 | pub fn reconstruct_limit(&self) -> usize { 66 | self.threshold + 1 67 | } 68 | 69 | /// Generate `share_count` shares from `secret`. 70 | pub fn share(&self, secret: i64) -> Vec { 71 | let poly = self.sample_polynomial(secret); 72 | self.evaluate_polynomial(&poly) 73 | } 74 | 75 | /// Reconstruct `secret` from a large enough subset of the shares. 76 | /// 77 | /// `indices` are the ranks of the known shares as output by the `share` method, 78 | /// while `values` are the actual values of these shares. 79 | /// Both must have the same number of elements, and at least `reconstruct_limit`. 80 | pub fn reconstruct(&self, indices: &[usize], shares: &[i64]) -> i64 { 81 | assert!(shares.len() == indices.len()); 82 | assert!(shares.len() >= self.reconstruct_limit()); 83 | // add one to indices to get points 84 | let points: Vec = indices.iter().map(|&i| (i as i64) + 1i64).collect(); 85 | lagrange_interpolation_at_zero(&*points, &shares, self.prime) 86 | } 87 | 88 | fn sample_polynomial(&self, zero_value: i64) -> Vec { 89 | // fix the first coefficient (corresponding to the evaluation at zero) 90 | let mut coefficients = vec![zero_value]; 91 | // sample the remaining coefficients randomly using secure randomness 92 | use rand::distributions::Sample; 93 | let mut range = rand::distributions::range::Range::new(0, self.prime - 1); 94 | let mut rng = rand::OsRng::new().unwrap(); 95 | let random_coefficients: Vec = 96 | (0..self.threshold).map(|_| range.sample(&mut rng)).collect(); 97 | coefficients.extend(random_coefficients); 98 | // return 99 | coefficients 100 | } 101 | 102 | fn evaluate_polynomial(&self, coefficients: &[i64]) -> Vec { 103 | // evaluate at all points 104 | (1..self.share_count + 1) 105 | .map(|point| mod_evaluate_polynomial(coefficients, point as i64, self.prime)) 106 | .collect() 107 | } 108 | } 109 | 110 | 111 | #[test] 112 | fn test_evaluate_polynomial() { 113 | let ref tss = SHAMIR_5_20; 114 | let poly = vec![1, 2, 0]; 115 | let values = tss.evaluate_polynomial(&poly); 116 | assert_eq!(*values, 117 | [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 0]); 118 | } 119 | 120 | #[test] 121 | fn wikipedia_example() { 122 | let tss = ShamirSecretSharing { 123 | threshold: 2, 124 | share_count: 6, 125 | prime: 1613, 126 | }; 127 | 128 | let shares = tss.evaluate_polynomial(&[1234, 166, 94]); 129 | assert_eq!(&*shares, &[1494, 329, 965, 176, 1188, 775]); 130 | 131 | assert_eq!(tss.reconstruct(&[0, 1, 2], &shares[0..3]), 1234); 132 | assert_eq!(tss.reconstruct(&[1, 2, 3], &shares[1..4]), 1234); 133 | assert_eq!(tss.reconstruct(&[2, 3, 4], &shares[2..5]), 1234); 134 | } 135 | 136 | #[test] 137 | fn test_shamir() { 138 | let tss = ShamirSecretSharing { 139 | threshold: 2, 140 | share_count: 6, 141 | prime: 41, 142 | }; 143 | let secret = 1; 144 | let shares = tss.share(secret); 145 | assert_eq!(tss.reconstruct(&[0, 1, 2], &shares[0..3]), secret); 146 | assert_eq!(tss.reconstruct(&[1, 2, 3], &shares[1..4]), secret); 147 | assert_eq!(tss.reconstruct(&[2, 3, 4, 5], &shares[2..6]), secret); 148 | } 149 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Threshold Secret Sharing 2 | 3 | [![Build Status](https://travis-ci.org/snipsco/rust-threshold-secret-sharing.svg?branch=master)](https://travis-ci.org/snipsco/rust-threshold-secret-sharing) 4 | [![Latest version](https://img.shields.io/crates/v/threshold-secret-sharing.svg)](https://img.shields.io/crates/v/threshold-secret-sharing.svg) 5 | [![License: MIT/Apache2](https://img.shields.io/badge/license-MIT%2fApache2-blue.svg)](https://img.shields.io/badge/license-MIT%2fApache2-blue.svg) 6 | 7 | Efficient pure-Rust library for [secret sharing](https://en.wikipedia.org/wiki/Secret_sharing), offering efficient share generation and reconstruction for both traditional Shamir sharing and packet sharing. For now, secrets and shares are fixed as prime field elements represented by `i64` values. 8 | 9 | 10 | # Installation 11 | 12 | 13 | ## Cargo 14 | ```toml 15 | [dependencies] 16 | threshold-secret-sharing = "0.2" 17 | ``` 18 | 19 | 20 | ## GitHub 21 | ```bash 22 | git clone https://github.com/snipsco/rust-threshold-secret-sharing 23 | cd rust-threshold-secret-sharing 24 | cargo build --release 25 | ``` 26 | 27 | 28 | # Examples 29 | Several examples are included in the `examples/` directory. Run each with `cargo` using e.g. 30 | ```sh 31 | cargo run --example shamir 32 | ``` 33 | for the Shamir example below. 34 | 35 | 36 | ## Shamir sharing 37 | Using the Shamir scheme is relatively straight-forward. 38 | 39 | When choosing parameters, `threshold` and `share_count` must be chosen to satisfy security requirements, and `prime` must be large enough to correctly encode the value to be shared (and such that `prime >= share_count + 1`). 40 | 41 | When reconstructing the secret, indices must be explicitly provided to identify the shares; these correspond to the indices the shares had in the vector returned by `share()`. 42 | 43 | ```rust 44 | extern crate threshold_secret_sharing as tss; 45 | 46 | fn main() { 47 | // create instance of the Shamir scheme 48 | let ref tss = tss::shamir::ShamirSecretSharing { 49 | threshold: 8, // privacy threshold 50 | share_count: 20, // total number of shares to generate 51 | prime: 41 // prime field to use 52 | }; 53 | 54 | let secret = 5; 55 | 56 | // generate shares for secret 57 | let all_shares = tss.share(secret); 58 | 59 | // artificially remove some of the shares 60 | let number_of_recovered_shared = 10; 61 | assert!(number_of_recovered_shared >= tss.reconstruct_limit()); 62 | let recovered_indices: Vec = (0..number_of_recovered_shared).collect(); 63 | let recovered_shares: &[i64] = &all_shares[0..number_of_recovered_shared]; 64 | 65 | // reconstruct using remaining subset of shares 66 | let reconstructed_secret = tss.reconstruct(&recovered_indices, recovered_shares); 67 | assert_eq!(reconstructed_secret, secret); 68 | } 69 | ``` 70 | 71 | 72 | ## Packed sharing 73 | If many secrets are to be secret shared, it may be beneficial to use the packed scheme where several secrets are packed into each share. While still very computational efficient, one downside is that the parameters are somewhat restricted. 74 | 75 | Specifically, the parameters are split in *scheme parameters* and *implementation parameters*: 76 | - the former, like in Shamir sharing, determines the abstract properties of the scheme, yet now also with a `secret_count` specifying how many secrets are to be packed into each share; the reconstruction limit is implicitly defined as `secret_count + threshold + 1` 77 | - the latter is related to the implementation (currently based on the Fast Fourier Transform) and requires not only a `prime` specifying the field, but also two principal roots of unity within that field, which must be respectively a power of 2 and a power of 3 78 | 79 | Due to this increased complexity, providing helper functions for finding suitable parameters are in progress. For now, a few fixed fields are included in the `packed` module as illustrated in the example below: 80 | 81 | - `PSS_4_8_3`, `PSS_4_26_3`, `PSS_155_728_100`, `PSS_155_19682_100` 82 | 83 | with format `PSS_T_N_D` for sharing `D` secrets into `N` shares with a threshold of `T`. 84 | 85 | ```rust 86 | extern crate threshold_secret_sharing as tss; 87 | 88 | fn main() { 89 | // use predefined parameters 90 | let ref tss = tss::packed::PSS_4_26_3; 91 | 92 | // generate shares for a vector of secrets 93 | let secrets = [1, 2, 3]; 94 | let all_shares = tss.share(&secrets); 95 | 96 | // artificially remove some of the shares; keep only the first 8 97 | let indices: Vec = (0..8).collect(); 98 | let shares = &all_shares[0..8]; 99 | 100 | // reconstruct using remaining subset of shares 101 | let recovered_secrets = tss.reconstruct(&indices, shares); 102 | assert_eq!(recovered_secrets, vec![1, 2, 3]); 103 | } 104 | ``` 105 | 106 | 107 | ## Homomorphic properties 108 | Both the Shamir and the packed scheme enjoy certain homomorphic properties: shared secrets can be transformed by manipulating the shares. Both addition and multiplications work, yet notice that the reconstruction limit in the case of multiplication goes up by a factor of two for each application. 109 | 110 | ```rust 111 | extern crate threshold_secret_sharing as tss; 112 | 113 | fn main() { 114 | // use predefined parameters 115 | let ref tss = tss::PSS_4_26_3; 116 | 117 | // generate shares for first vector of secrets 118 | let secrets_1 = [1, 2, 3]; 119 | let shares_1 = tss.share(&secrets_1); 120 | 121 | // generate shares for second vector of secrets 122 | let secrets_2 = [4, 5, 6]; 123 | let shares_2 = tss.share(&secrets_2); 124 | 125 | // combine shares pointwise to get shares of the sum of the secrets 126 | let shares_sum: Vec = shares_1.iter().zip(&shares_2) 127 | .map(|(a, b)| (a + b) % tss.prime).collect(); 128 | 129 | // artificially remove some of the shares; keep only the first 8 130 | let indices: Vec = (0..8).collect(); 131 | let shares = &shares_sum[0..8]; 132 | 133 | // reconstruct using remaining subset of shares 134 | let recovered_secrets = tss.reconstruct(&indices, shares); 135 | assert_eq!(recovered_secrets, vec![5, 7, 9]); 136 | } 137 | ``` 138 | 139 | # Parameter generation 140 | While it's straight-forward to instantiate the Shamir scheme, as mentioned above the packed scheme is more tricky and a few helper methods are provided as a result. Since some applications needs only a fixed choice of parameters, these helper methods are optional and only included if the `paramgen` feature is activated during compilation: 141 | ``` 142 | cargo build --features paramgen 143 | ``` 144 | which also adds several extra dependencies. 145 | 146 | 147 | # Performance 148 | So far most performance efforts has been focused on share generation for the packed scheme, with some obvious enhancements for reconstruction in the process of being implemented. As an example, sharing 100 secrets into approximately 20,000 shares with the packed scheme runs in around 31ms on a recent laptop, and in around 590ms on a Raspberry Pi 3. 149 | 150 | These numbers were obtained by running 151 | ``` 152 | cargo bench 153 | ``` 154 | using the nightly toolchain. 155 | 156 | # License 157 | 158 | Licensed under either of 159 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 160 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 161 | at your option. 162 | 163 | ## Contribution 164 | 165 | Unless you explicitly state otherwise, any contribution intentionally submitted 166 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall 167 | be dual licensed as above, without any additional terms or conditions. 168 | -------------------------------------------------------------------------------- /src/fields/fft.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 rust-threshold-secret-sharing developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 4 | // or the MIT 5 | // license , at your 6 | // option. All files in the project carrying such notice may not be copied, 7 | // modified, or distributed except according to those terms. 8 | 9 | //! FFT by in-place Cooley-Tukey algorithms. 10 | 11 | use super::Field; 12 | 13 | /// 2-radix FFT. 14 | /// 15 | /// * zp is the modular field 16 | /// * data is the data to transform 17 | /// * omega is the root-of-unity to use 18 | /// 19 | /// `data.len()` must be a power of 2. omega must be a root of unity of order 20 | /// `data.len()` 21 | pub fn fft2(zp: &F, data: &mut [F::U], omega: F::U) { 22 | fft2_in_place_rearrange(zp, &mut *data); 23 | fft2_in_place_compute(zp, &mut *data, omega); 24 | } 25 | 26 | /// 2-radix inverse FFT. 27 | /// 28 | /// * zp is the modular field 29 | /// * data is the data to transform 30 | /// * omega is the root-of-unity to use 31 | /// 32 | /// `data.len()` must be a power of 2. omega must be a root of unity of order 33 | /// `data.len()` 34 | pub fn fft2_inverse(zp: &F, data: &mut [F::U], omega: F::U) { 35 | let omega_inv = zp.inv(omega); 36 | let len = data.len(); 37 | let len_inv = zp.inv(zp.from_u64(len as u64)); 38 | fft2(zp, data, omega_inv); 39 | for mut x in data { 40 | *x = zp.mul(*x, len_inv); 41 | } 42 | } 43 | 44 | fn fft2_in_place_rearrange(_zp: &F, data: &mut [F::U]) { 45 | let mut target = 0; 46 | for pos in 0..data.len() { 47 | if target > pos { 48 | data.swap(target, pos) 49 | } 50 | let mut mask = data.len() >> 1; 51 | while target & mask != 0 { 52 | target &= !mask; 53 | mask >>= 1; 54 | } 55 | target |= mask; 56 | } 57 | } 58 | 59 | fn fft2_in_place_compute(zp: &F, data: &mut [F::U], omega: F::U) { 60 | let mut depth = 0usize; 61 | while 1usize << depth < data.len() { 62 | let step = 1usize << depth; 63 | let jump = 2 * step; 64 | let factor_stride = zp.qpow(omega, (data.len() / step / 2) as u32); 65 | let mut factor = zp.one(); 66 | for group in 0usize..step { 67 | let mut pair = group; 68 | while pair < data.len() { 69 | let (x, y) = (data[pair], zp.mul(data[pair + step], factor)); 70 | 71 | data[pair] = zp.add(x, y); 72 | data[pair + step] = zp.sub(x, y); 73 | 74 | pair += jump; 75 | } 76 | factor = zp.mul(factor, factor_stride); 77 | } 78 | depth += 1; 79 | } 80 | } 81 | 82 | fn trigits_len(n: usize) -> usize { 83 | let mut result = 1; 84 | let mut value = 3; 85 | while value < n + 1 { 86 | result += 1; 87 | value *= 3; 88 | } 89 | result 90 | } 91 | 92 | fn fft3_in_place_rearrange(_zp: &F, data: &mut [F::U]) { 93 | let mut target = 0isize; 94 | let trigits_len = trigits_len(data.len() - 1); 95 | let mut trigits: Vec = ::std::iter::repeat(0).take(trigits_len).collect(); 96 | let powers: Vec = (0..trigits_len).map(|x| 3isize.pow(x as u32)).rev().collect(); 97 | for pos in 0..data.len() { 98 | if target as usize > pos { 99 | data.swap(target as usize, pos) 100 | } 101 | for pow in 0..trigits_len { 102 | if trigits[pow] < 2 { 103 | trigits[pow] += 1; 104 | target += powers[pow]; 105 | break; 106 | } else { 107 | trigits[pow] = 0; 108 | target -= 2 * powers[pow]; 109 | } 110 | } 111 | } 112 | } 113 | 114 | fn fft3_in_place_compute(zp: &F, data: &mut [F::U], omega: F::U) { 115 | let mut step = 1; 116 | let big_omega = zp.qpow(omega, (data.len() as u32 / 3)); 117 | let big_omega_sq = zp.mul(big_omega, big_omega); 118 | while step < data.len() { 119 | let jump = 3 * step; 120 | let factor_stride = zp.qpow(omega, (data.len() / step / 3) as u32); 121 | let mut factor = zp.one(); 122 | for group in 0usize..step { 123 | let factor_sq = zp.mul(factor, factor); 124 | let mut pair = group; 125 | while pair < data.len() { 126 | let (x, y, z) = (data[pair], 127 | zp.mul(data[pair + step], factor), 128 | zp.mul(data[pair + 2 * step], factor_sq)); 129 | 130 | data[pair] = zp.add(zp.add(x, y), z); 131 | data[pair + step] = 132 | zp.add(zp.add(x, zp.mul(big_omega, y)), zp.mul(big_omega_sq, z)); 133 | data[pair + 2 * step] = 134 | zp.add(zp.add(x, zp.mul(big_omega_sq, y)), zp.mul(big_omega, z)); 135 | 136 | pair += jump; 137 | } 138 | factor = zp.mul(factor, factor_stride); 139 | } 140 | step = jump; 141 | } 142 | } 143 | 144 | /// 3-radix FFT. 145 | /// 146 | /// * zp is the modular field 147 | /// * data is the data to transform 148 | /// * omega is the root-of-unity to use 149 | /// 150 | /// `data.len()` must be a power of 2. omega must be a root of unity of order 151 | /// `data.len()` 152 | pub fn fft3(zp: &F, data: &mut [F::U], omega: F::U) { 153 | fft3_in_place_rearrange(zp, &mut *data); 154 | fft3_in_place_compute(zp, &mut *data, omega); 155 | } 156 | 157 | /// 3-radix inverse FFT. 158 | /// 159 | /// * zp is the modular field 160 | /// * data is the data to transform 161 | /// * omega is the root-of-unity to use 162 | /// 163 | /// `data.len()` must be a power of 2. omega must be a root of unity of order 164 | /// `data.len()` 165 | pub fn fft3_inverse(zp: &F, data: &mut [F::U], omega: F::U) { 166 | let omega_inv = zp.inv(omega); 167 | let len_inv = zp.inv(zp.from_u64(data.len() as u64)); 168 | fft3(zp, data, omega_inv); 169 | for mut x in data { 170 | *x = zp.mul(*x, len_inv); 171 | } 172 | } 173 | 174 | #[cfg(test)] 175 | pub mod test { 176 | use super::*; 177 | use fields::Field; 178 | 179 | pub fn from(zp: &F, data: &[u64]) -> Vec { 180 | data.iter().map(|&x| zp.from_u64(x)).collect() 181 | } 182 | 183 | pub fn back(zp: &F, data: &[F::U]) -> Vec { 184 | data.iter().map(|&x| zp.to_u64(x)).collect() 185 | } 186 | 187 | pub fn test_fft2() { 188 | // field is Z_433 in which 354 is an 8th root of unity 189 | let zp = F::new(433); 190 | let omega = zp.from_u64(354); 191 | 192 | let mut data = from(&zp, &[1, 2, 3, 4, 5, 6, 7, 8]); 193 | fft2(&zp, &mut data, omega); 194 | assert_eq!(back(&zp, &data), [36, 303, 146, 3, 429, 422, 279, 122]); 195 | } 196 | 197 | pub fn test_fft2_inverse() { 198 | // field is Z_433 in which 354 is an 8th root of unity 199 | let zp = F::new(433); 200 | let omega = zp.from_u64(354); 201 | 202 | let mut data = from(&zp, &[36, 303, 146, 3, 429, 422, 279, 122]); 203 | fft2_inverse(&zp, &mut *data, omega); 204 | assert_eq!(back(&zp, &data), [1, 2, 3, 4, 5, 6, 7, 8]) 205 | } 206 | 207 | pub fn test_fft2_big() { 208 | let zp = F::new(5038849); 209 | let omega = zp.from_u64(4318906); 210 | 211 | let mut data: Vec<_> = (0..256).map(|a| zp.from_u64(a)).collect(); 212 | fft2(&zp, &mut *data, omega); 213 | fft2_inverse(&zp, &mut data, omega); 214 | 215 | assert_eq!(back(&zp, &data), (0..256).collect::>()); 216 | } 217 | 218 | pub fn test_fft3() { 219 | // field is Z_433 in which 150 is an 9th root of unity 220 | let zp = F::new(433); 221 | let omega = zp.from_u64(150); 222 | 223 | let mut data = from(&zp, &[1, 2, 3, 4, 5, 6, 7, 8, 9]); 224 | fft3(&zp, &mut data, omega); 225 | assert_eq!(back(&zp, &data), [45, 404, 407, 266, 377, 47, 158, 17, 20]); 226 | } 227 | 228 | pub fn test_fft3_inverse() { 229 | // field is Z_433 in which 150 is an 9th root of unity 230 | let zp = F::new(433); 231 | let omega = zp.from_u64(150); 232 | 233 | let mut data = from(&zp, &[45, 404, 407, 266, 377, 47, 158, 17, 20]); 234 | fft3_inverse(&zp, &mut *data, omega); 235 | assert_eq!(back(&zp, &data), [1, 2, 3, 4, 5, 6, 7, 8, 9]) 236 | } 237 | 238 | pub fn test_fft3_big() { 239 | let zp = F::new(5038849); 240 | let omega = zp.from_u64(1814687); 241 | 242 | let mut data: Vec<_> = (0..19683).map(|a| zp.from_u64(a)).collect(); 243 | fft3(&zp, &mut data, omega); 244 | fft3_inverse(&zp, &mut data, omega); 245 | 246 | assert_eq!(back(&zp, &data), (0..19683).collect::>()); 247 | } 248 | } 249 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/numtheory.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 rust-threshold-secret-sharing developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 4 | // or the MIT 5 | // license , at your 6 | // option. All files in the project carrying such notice may not be copied, 7 | // modified, or distributed except according to those terms. 8 | 9 | //! Various number theoretic utility functions used in the library. 10 | 11 | /// Euclidean GCD implementation (recursive). The first member of the returned 12 | /// triplet is the GCD of `a` and `b`. 13 | pub fn gcd(a: i64, b: i64) -> (i64, i64, i64) { 14 | if b == 0 { 15 | (a, 1, 0) 16 | } else { 17 | let n = a / b; 18 | let c = a % b; 19 | let r = gcd(b, c); 20 | (r.0, r.2, r.1 - r.2 * n) 21 | } 22 | } 23 | 24 | #[test] 25 | fn test_gcd() { 26 | assert_eq!(gcd(12, 16), (4, -1, 1)); 27 | } 28 | 29 | 30 | /// Inverse of `k` in the *Zp* field defined by `prime`. 31 | pub fn mod_inverse(k: i64, prime: i64) -> i64 { 32 | let k2 = k % prime; 33 | let r = if k2 < 0 { 34 | -gcd(prime, -k2).2 35 | } else { 36 | gcd(prime, k2).2 37 | }; 38 | (prime + r) % prime 39 | } 40 | 41 | #[test] 42 | fn test_mod_inverse() { 43 | assert_eq!(mod_inverse(3, 7), 5); 44 | } 45 | 46 | 47 | /// `x` to the power of `e` in the *Zp* field defined by `prime`. 48 | pub fn mod_pow(mut x: i64, mut e: u32, prime: i64) -> i64 { 49 | let mut acc = 1; 50 | while e > 0 { 51 | if e % 2 == 0 { 52 | // even 53 | // no-op 54 | } else { 55 | // odd 56 | acc = (acc * x) % prime; 57 | } 58 | x = (x * x) % prime; // waste one of these by having it here but code is simpler (tiny bit) 59 | e = e >> 1; 60 | } 61 | acc 62 | } 63 | 64 | #[test] 65 | fn test_mod_pow() { 66 | assert_eq!(mod_pow(2, 0, 17), 1); 67 | assert_eq!(mod_pow(2, 3, 17), 8); 68 | assert_eq!(mod_pow(2, 6, 17), 13); 69 | 70 | assert_eq!(mod_pow(-3, 0, 17), 1); 71 | assert_eq!(mod_pow(-3, 1, 17), -3); 72 | assert_eq!(mod_pow(-3, 15, 17), -6); 73 | } 74 | 75 | 76 | /// Compute the 2-radix FFT of `a_coef` in the *Zp* field defined by `prime`. 77 | /// 78 | /// `omega` must be a `n`-th principal root of unity, 79 | /// where `n` is the lenght of `a_coef` as well as a power of 2. 80 | /// The result will contains the same number of elements. 81 | #[allow(dead_code)] 82 | pub fn fft2(a_coef: &[i64], omega: i64, prime: i64) -> Vec { 83 | use fields::Field; 84 | let zp = ::fields::montgomery::MontgomeryField32::new(prime as u32); 85 | 86 | let mut data = a_coef.iter().map(|&a| zp.from_i64(a)).collect::>(); 87 | ::fields::fft::fft2(&zp, &mut *data, zp.from_i64(omega)); 88 | data.iter().map(|a| zp.to_i64(*a)).collect() 89 | } 90 | 91 | /// Inverse FFT for `fft2`. 92 | pub fn fft2_inverse(a_point: &[i64], omega: i64, prime: i64) -> Vec { 93 | use fields::Field; 94 | let zp = ::fields::montgomery::MontgomeryField32::new(prime as u32); 95 | 96 | let mut data = a_point.iter().map(|&a| zp.from_i64(a)).collect::>(); 97 | ::fields::fft::fft2_inverse(&zp, &mut *data, zp.from_i64(omega)); 98 | data.iter().map(|a| zp.to_i64(*a)).collect() 99 | } 100 | 101 | #[test] 102 | fn test_fft2() { 103 | // field is Z_433 in which 354 is an 8th root of unity 104 | let prime = 433; 105 | let omega = 354; 106 | 107 | let a_coef = vec![1, 2, 3, 4, 5, 6, 7, 8]; 108 | let a_point = fft2(&a_coef, omega, prime); 109 | assert_eq!(positivise(&a_point, prime), 110 | positivise(&[36, -130, -287, 3, -4, 422, 279, -311], prime)) 111 | } 112 | 113 | #[test] 114 | fn test_fft2_inverse() { 115 | // field is Z_433 in which 354 is an 8th root of unity 116 | let prime = 433; 117 | let omega = 354; 118 | 119 | let a_point = vec![36, -130, -287, 3, -4, 422, 279, -311]; 120 | let a_coef = fft2_inverse(&a_point, omega, prime); 121 | assert_eq!(positivise(&a_coef, prime), vec![1, 2, 3, 4, 5, 6, 7, 8]) 122 | } 123 | 124 | /// Compute the 3-radix FFT of `a_coef` in the *Zp* field defined by `prime`. 125 | /// 126 | /// `omega` must be a `n`-th principal root of unity, 127 | /// where `n` is the lenght of `a_coef` as well as a power of 3. 128 | /// The result will contains the same number of elements. 129 | pub fn fft3(a_coef: &[i64], omega: i64, prime: i64) -> Vec { 130 | use fields::Field; 131 | let zp = ::fields::montgomery::MontgomeryField32::new(prime as u32); 132 | 133 | let mut data = a_coef.iter().map(|&a| zp.from_i64(a)).collect::>(); 134 | ::fields::fft::fft3(&zp, &mut *data, zp.from_i64(omega)); 135 | data.iter().map(|a| zp.to_i64(*a)).collect() 136 | } 137 | 138 | /// Inverse FFT for `fft3`. 139 | #[allow(dead_code)] 140 | pub fn fft3_inverse(a_point: &[i64], omega: i64, prime: i64) -> Vec { 141 | use fields::Field; 142 | let zp = ::fields::montgomery::MontgomeryField32::new(prime as u32); 143 | 144 | let mut data = a_point.iter().map(|&a| zp.from_i64(a)).collect::>(); 145 | ::fields::fft::fft3_inverse(&zp, &mut *data, zp.from_i64(omega)); 146 | data.iter().map(|a| zp.to_i64(*a)).collect() 147 | } 148 | 149 | #[test] 150 | fn test_fft3() { 151 | // field is Z_433 in which 150 is an 9th root of unity 152 | let prime = 433; 153 | let omega = 150; 154 | 155 | let a_coef = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; 156 | let a_point = positivise(&fft3(&a_coef, omega, prime), prime); 157 | assert_eq!(a_point, vec![45, 404, 407, 266, 377, 47, 158, 17, 20]) 158 | } 159 | 160 | #[test] 161 | fn test_fft3_inverse() { 162 | // field is Z_433 in which 150 is an 9th root of unity 163 | let prime = 433; 164 | let omega = 150; 165 | 166 | let a_point = vec![45, 404, 407, 266, 377, 47, 158, 17, 20]; 167 | let a_coef = positivise(&fft3_inverse(&a_point, omega, prime), prime); 168 | assert_eq!(a_coef, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]) 169 | } 170 | 171 | /// Performs a Lagrange interpolation in field Zp at the origin 172 | /// for a polynomial defined by `points` and `values`. 173 | /// 174 | /// `points` and `values` are expected to be two arrays of the same size, containing 175 | /// respectively the evaluation points (x) and the value of the polynomial at those point (p(x)). 176 | /// 177 | /// The result is the value of the polynomial at x=0. It is also its zero-degree coefficient. 178 | /// 179 | /// This is obviously less general than `newton_interpolation_general` as we 180 | /// only get a single value, but it is much faster. 181 | pub fn lagrange_interpolation_at_zero(points: &[i64], values: &[i64], prime: i64) -> i64 { 182 | assert_eq!(points.len(), values.len()); 183 | // Lagrange interpolation for point 0 184 | let mut acc = 0i64; 185 | for i in 0..values.len() { 186 | let xi = points[i]; 187 | let yi = values[i]; 188 | let mut num = 1i64; 189 | let mut denum = 1i64; 190 | for j in 0..values.len() { 191 | if j != i { 192 | let xj = points[j]; 193 | num = (num * xj) % prime; 194 | denum = (denum * (xj - xi)) % prime; 195 | } 196 | } 197 | acc = (acc + yi * num * mod_inverse(denum, prime)) % prime; 198 | } 199 | acc 200 | } 201 | 202 | /// Holds together points and Newton-interpolated coefficients for fast evaluation. 203 | pub struct NewtonPolynomial<'a> { 204 | points: &'a [i64], 205 | coefficients: Vec, 206 | } 207 | 208 | 209 | /// General case for Newton interpolation in field Zp. 210 | /// 211 | /// Given enough `points` (x) and `values` (p(x)), find the coefficients for `p`. 212 | pub fn newton_interpolation_general<'a>(points: &'a [i64], 213 | values: &[i64], 214 | prime: i64) 215 | -> NewtonPolynomial<'a> { 216 | let coefficients = compute_newton_coefficients(points, values, prime); 217 | NewtonPolynomial { 218 | points: points, 219 | coefficients: coefficients, 220 | } 221 | } 222 | 223 | #[test] 224 | fn test_newton_interpolation_general() { 225 | let prime = 17; 226 | 227 | let poly = [1, 2, 3, 4]; 228 | let points = vec![5, 6, 7, 8, 9]; 229 | let values: Vec = 230 | points.iter().map(|&point| mod_evaluate_polynomial(&poly, point, prime)).collect(); 231 | assert_eq!(values, vec![8, 16, 4, 13, 16]); 232 | 233 | let recovered_poly = newton_interpolation_general(&points, &values, prime); 234 | let recovered_values: Vec = 235 | points.iter().map(|&point| newton_evaluate(&recovered_poly, point, prime)).collect(); 236 | assert_eq!(recovered_values, values); 237 | 238 | assert_eq!(newton_evaluate(&recovered_poly, 10, prime), 3); 239 | assert_eq!(newton_evaluate(&recovered_poly, 11, prime), -2); 240 | assert_eq!(newton_evaluate(&recovered_poly, 12, prime), 8); 241 | } 242 | 243 | pub fn newton_evaluate(poly: &NewtonPolynomial, point: i64, prime: i64) -> i64 { 244 | // compute Newton points 245 | let mut newton_points = vec![1]; 246 | for i in 0..poly.points.len() - 1 { 247 | let diff = (point - poly.points[i]) % prime; 248 | let product = (newton_points[i] * diff) % prime; 249 | newton_points.push(product); 250 | } 251 | let ref newton_coefs = poly.coefficients; 252 | // sum up 253 | newton_coefs.iter() 254 | .zip(newton_points) 255 | .map(|(coef, point)| (coef * point) % prime) 256 | .fold(0, |a, b| (a + b) % prime) 257 | } 258 | 259 | fn compute_newton_coefficients(points: &[i64], values: &[i64], prime: i64) -> Vec { 260 | assert_eq!(points.len(), values.len()); 261 | 262 | let mut store: Vec<(usize, usize, i64)> = 263 | values.iter().enumerate().map(|(index, &value)| (index, index, value)).collect(); 264 | 265 | for j in 1..store.len() { 266 | for i in (j..store.len()).rev() { 267 | let index_lower = store[i - 1].0; 268 | let index_upper = store[i].1; 269 | 270 | let point_lower = points[index_lower]; 271 | let point_upper = points[index_upper]; 272 | let point_diff = (point_upper - point_lower) % prime; 273 | let point_diff_inverse = mod_inverse(point_diff, prime); 274 | 275 | let coef_lower = store[i - 1].2; 276 | let coef_upper = store[i].2; 277 | let coef_diff = (coef_upper - coef_lower) % prime; 278 | 279 | let fraction = (coef_diff * point_diff_inverse) % prime; 280 | 281 | store[i] = (index_lower, index_upper, fraction); 282 | } 283 | } 284 | 285 | store.iter().map(|&(_, _, v)| v).collect() 286 | } 287 | 288 | #[test] 289 | fn test_compute_newton_coefficients() { 290 | let points = vec![5, 6, 7, 8, 9]; 291 | let values = vec![8, 16, 4, 13, 16]; 292 | let prime = 17; 293 | 294 | let coefficients = compute_newton_coefficients(&points, &values, prime); 295 | assert_eq!(coefficients, vec![8, 8, -10, 4, 0]); 296 | } 297 | 298 | /// Map `values` from `[-n/2, n/2)` to `[0, n)`. 299 | pub fn positivise(values: &[i64], n: i64) -> Vec { 300 | values.iter() 301 | .map(|&value| if value < 0 { value + n } else { value }) 302 | .collect() 303 | } 304 | 305 | // deprecated 306 | // fn mod_evaluate_polynomial_naive(coefficients: &[i64], point: i64, prime: i64) -> i64 { 307 | // // evaluate naively 308 | // coefficients.iter() 309 | // .enumerate() 310 | // .map(|(deg, coef)| (coef * mod_pow(point, deg as u32, prime)) % prime) 311 | // .fold(0, |a, b| (a + b) % prime) 312 | // } 313 | // 314 | // #[test] 315 | // fn test_mod_evaluate_polynomial_naive() { 316 | // let poly = vec![1,2,3,4,5,6]; 317 | // let point = 5; 318 | // let prime = 17; 319 | // assert_eq!(mod_evaluate_polynomial_naive(&poly, point, prime), 4); 320 | // } 321 | 322 | /// Evaluate polynomial given by `coefficients` at `point` in Zp using Horner's method. 323 | pub fn mod_evaluate_polynomial(coefficients: &[i64], point: i64, prime: i64) -> i64 { 324 | // evaluate using Horner's rule 325 | // - to combine with fold we consider the coefficients in reverse order 326 | let mut reversed_coefficients = coefficients.iter().rev(); 327 | // manually split due to fold insisting on an initial value 328 | let head = *reversed_coefficients.next().unwrap(); 329 | let tail = reversed_coefficients; 330 | tail.fold(head, |partial, coef| (partial * point + coef) % prime) 331 | } 332 | 333 | #[test] 334 | fn test_mod_evaluate_polynomial() { 335 | let poly = vec![1, 2, 3, 4, 5, 6]; 336 | let point = 5; 337 | let prime = 17; 338 | assert_eq!(mod_evaluate_polynomial(&poly, point, prime), 4); 339 | } 340 | -------------------------------------------------------------------------------- /src/packed.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 rust-threshold-secret-sharing developers 2 | // 3 | // Licensed under the Apache License, Version 2.0 4 | // or the MIT 5 | // license , at your 6 | // option. All files in the project carrying such notice may not be copied, 7 | // modified, or distributed except according to those terms. 8 | 9 | //! Packed (or ramp) variant of Shamir secret sharing, 10 | //! allowing efficient sharing of several secrets together. 11 | 12 | use numtheory::{mod_pow, fft2_inverse, fft3}; 13 | use rand; 14 | 15 | /// Parameters for the packed variant of Shamir secret sharing, 16 | /// specifying number of secrets shared together, total number of shares, and privacy threshold. 17 | /// 18 | /// This scheme generalises 19 | /// [Shamir's scheme](https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing) 20 | /// by simultaneously sharing several secrets, at the expense of leaving a gap 21 | /// between the privacy threshold and the reconstruction limit. 22 | /// 23 | /// The Fast Fourier Transform is used for efficiency reasons, 24 | /// allowing most operations run to quasilinear time `O(n.log(n))` in `share_count`. 25 | /// An implication of this is that secrets and shares are positioned on positive powers of 26 | /// respectively an `n`-th and `m`-th principal root of unity, 27 | /// where `n` is a power of 2 and `m` a power of 3. 28 | /// 29 | /// As a result there exist several constraints between the various parameters: 30 | /// 31 | /// * `prime` must be a prime large enough to hold the secrets we plan to share 32 | /// * `share_count` must be at least `secret_count + threshold` (the reconstruction limit) 33 | /// * `secret_count + threshold + 1` must be a power of 2 34 | /// * `share_count + 1` must be a power of 3 35 | /// * `omega_secrets` must be a `(secret_count + threshold + 1)`-th root of unity 36 | /// * `omega_shares` must be a `(share_count + 1)`-th root of unity 37 | /// 38 | /// An optional `paramgen` feature provides methods for finding suitable parameters satisfying 39 | /// these somewhat complex requirements, in addition to several fixed parameter choices. 40 | #[derive(Debug,Copy,Clone,PartialEq)] 41 | pub struct PackedSecretSharing { 42 | 43 | // abstract properties 44 | 45 | /// Maximum number of shares that can be known without exposing the secrets 46 | /// (privacy threshold). 47 | pub threshold: usize, 48 | /// Number of shares to split the secrets into. 49 | pub share_count: usize, 50 | /// Number of secrets to share together. 51 | pub secret_count: usize, 52 | 53 | // implementation configuration 54 | 55 | /// Prime defining the Zp field in which computation is taking place. 56 | pub prime: i64, 57 | /// `m`-th principal root of unity in Zp, where `m = secret_count + threshold + 1` 58 | /// must be a power of 2. 59 | pub omega_secrets: i64, 60 | /// `n`-th principal root of unity in Zp, where `n = share_count + 1` must be a power of 3. 61 | pub omega_shares: i64, 62 | } 63 | 64 | /// Example of tiny PSS settings, for sharing 3 secrets into 8 shares, with 65 | /// a privacy threshold of 4. 66 | pub static PSS_4_8_3: PackedSecretSharing = PackedSecretSharing { 67 | threshold: 4, 68 | share_count: 8, 69 | secret_count: 3, 70 | prime: 433, 71 | omega_secrets: 354, 72 | omega_shares: 150, 73 | }; 74 | 75 | /// Example of small PSS settings, for sharing 3 secrets into 26 shares, with 76 | /// a privacy threshold of 4. 77 | pub static PSS_4_26_3: PackedSecretSharing = PackedSecretSharing { 78 | threshold: 4, 79 | share_count: 26, 80 | secret_count: 3, 81 | prime: 433, 82 | omega_secrets: 354, 83 | omega_shares: 17, 84 | }; 85 | 86 | /// Example of PSS settings, for sharing 100 secrets into 728 shares, with 87 | /// a privacy threshold of 155. 88 | pub static PSS_155_728_100: PackedSecretSharing = PackedSecretSharing { 89 | threshold: 155, 90 | share_count: 728, 91 | secret_count: 100, 92 | prime: 746497, 93 | omega_secrets: 95660, 94 | omega_shares: 610121, 95 | }; 96 | 97 | /// Example of PSS settings, for sharing 100 secrets into 19682 shares, with 98 | /// a privacy threshold of 155. 99 | pub static PSS_155_19682_100: PackedSecretSharing = PackedSecretSharing { 100 | threshold: 155, 101 | share_count: 19682, 102 | secret_count: 100, 103 | prime: 5038849, 104 | omega_secrets: 4318906, 105 | omega_shares: 1814687, 106 | }; 107 | 108 | impl PackedSecretSharing { 109 | /// Minimum number of shares required to reconstruct secrets. 110 | /// 111 | /// For this scheme this is always `secret_count + threshold` 112 | pub fn reconstruct_limit(&self) -> usize { 113 | self.threshold + self.secret_count 114 | } 115 | 116 | /// Generate `share_count` shares for the `secrets` vector. 117 | /// 118 | /// The length of `secrets` must be `secret_count`. 119 | /// It is safe to pad with anything, including zeros. 120 | pub fn share(&self, secrets: &[i64]) -> Vec { 121 | assert_eq!(secrets.len(), self.secret_count); 122 | // sample polynomial 123 | let mut poly = self.sample_polynomial(secrets); 124 | assert_eq!(poly.len(), self.reconstruct_limit() + 1); 125 | // .. and extend it 126 | poly.extend(vec![0; self.share_count - self.reconstruct_limit()]); 127 | assert_eq!(poly.len(), self.share_count + 1); 128 | // evaluate polynomial to generate shares 129 | let mut shares = self.evaluate_polynomial(poly); 130 | // .. but remove first element since it should not be used as a share (it's always zero) 131 | assert_eq!(shares[0], 0); 132 | shares.remove(0); 133 | // return 134 | assert_eq!(shares.len(), self.share_count); 135 | shares 136 | } 137 | 138 | fn sample_polynomial(&self, secrets: &[i64]) -> Vec { 139 | assert_eq!(secrets.len(), self.secret_count); 140 | // sample randomness using secure randomness 141 | use rand::distributions::Sample; 142 | let mut range = rand::distributions::range::Range::new(0, self.prime - 1); 143 | let mut rng = rand::OsRng::new().unwrap(); 144 | let randomness: Vec = 145 | (0..self.threshold).map(|_| range.sample(&mut rng) as i64).collect(); 146 | // recover polynomial 147 | let coefficients = self.recover_polynomial(secrets, randomness); 148 | assert_eq!(coefficients.len(), self.reconstruct_limit() + 1); 149 | coefficients 150 | } 151 | 152 | fn recover_polynomial(&self, secrets: &[i64], randomness: Vec) -> Vec { 153 | // fix the value corresponding to point 1 (zero) 154 | let mut values: Vec = vec![0]; 155 | // let the subsequent values correspond to the secrets 156 | values.extend(secrets); 157 | // fill in with random values 158 | values.extend(randomness); 159 | // run backward FFT to recover polynomial in coefficient representation 160 | assert_eq!(values.len(), self.reconstruct_limit() + 1); 161 | let coefficients = fft2_inverse(&values, self.omega_secrets, self.prime); 162 | coefficients 163 | } 164 | 165 | fn evaluate_polynomial(&self, coefficients: Vec) -> Vec { 166 | assert_eq!(coefficients.len(), self.share_count + 1); 167 | let points = fft3(&coefficients, self.omega_shares, self.prime); 168 | points 169 | } 170 | 171 | /// Reconstruct the secrets from a large enough subset of the shares. 172 | /// 173 | /// `indices` are the ranks of the known shares as output by the `share` method, 174 | /// while `values` are the actual values of these shares. 175 | /// Both must have the same number of elements, and at least `reconstruct_limit`. 176 | /// 177 | /// The resulting vector is of length `secret_count`. 178 | pub fn reconstruct(&self, indices: &[usize], shares: &[i64]) -> Vec { 179 | assert!(shares.len() == indices.len()); 180 | assert!(shares.len() >= self.reconstruct_limit()); 181 | let mut points: Vec = 182 | indices.iter() 183 | .map(|&x| mod_pow(self.omega_shares, x as u32 + 1, self.prime)) 184 | .collect(); 185 | let mut values = shares.to_vec(); 186 | // insert missing value for point 1 (zero) 187 | points.insert(0, 1); 188 | values.insert(0, 0); 189 | // interpolate using Newton's method 190 | use numtheory::{newton_interpolation_general, newton_evaluate}; 191 | // TODO optimise by using Newton-equally-space variant 192 | let poly = newton_interpolation_general(&points, &values, self.prime); 193 | // evaluate at omega_secrets points to recover secrets 194 | // TODO optimise to avoid re-computation of power 195 | let secrets = (1..self.reconstruct_limit()) 196 | .map(|e| mod_pow(self.omega_secrets, e as u32, self.prime)) 197 | .map(|point| newton_evaluate(&poly, point, self.prime)) 198 | .take(self.secret_count) 199 | .collect(); 200 | secrets 201 | } 202 | } 203 | 204 | 205 | #[cfg(test)] 206 | mod tests { 207 | 208 | use super::*; 209 | use numtheory::*; 210 | 211 | #[test] 212 | fn test_recover_polynomial() { 213 | let ref pss = PSS_4_8_3; 214 | let secrets = vec![1, 2, 3]; 215 | let randomness = vec![8, 8, 8, 8]; // use fixed randomness 216 | let poly = pss.recover_polynomial(&secrets, randomness); 217 | assert_eq!( 218 | positivise(&poly, pss.prime), 219 | positivise(&[113, -382, -172, 267, -325, 432, 388, -321], pss.prime) 220 | ); 221 | } 222 | 223 | #[test] 224 | #[cfg_attr(rustfmt, rustfmt_skip)] 225 | fn test_evaluate_polynomial() { 226 | let ref pss = PSS_4_26_3; 227 | let poly = vec![113, 51, 261, 267, 108, 432, 388, 112, 0, 228 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 229 | 0, 0, 0, 0, 0, 0, 0, 0, 0]; 230 | let points = &pss.evaluate_polynomial(poly); 231 | assert_eq!( 232 | positivise(points, pss.prime), 233 | vec![ 0, 77, 230, 91, 286, 179, 337, 83, 212, 234 | 88, 406, 58, 425, 345, 350, 336, 430, 404, 235 | 51, 60, 305, 395, 84, 156, 160, 112, 422] 236 | ); 237 | } 238 | 239 | #[test] 240 | #[cfg_attr(rustfmt, rustfmt_skip)] 241 | fn test_share() { 242 | let ref pss = PSS_4_26_3; 243 | 244 | // do sharing 245 | let secrets = vec![5, 6, 7]; 246 | let mut shares = pss.share(&secrets); 247 | 248 | // manually recover secrets 249 | use numtheory::{fft3_inverse, mod_evaluate_polynomial}; 250 | shares.insert(0, 0); 251 | let poly = fft3_inverse(&shares, PSS_4_26_3.omega_shares, PSS_4_26_3.prime); 252 | let recovered_secrets: Vec = (1..secrets.len() + 1) 253 | .map(|i| { 254 | mod_evaluate_polynomial(&poly, 255 | mod_pow(PSS_4_26_3.omega_secrets, 256 | i as u32, 257 | PSS_4_26_3.prime), 258 | PSS_4_26_3.prime) 259 | }) 260 | .collect(); 261 | 262 | use numtheory::positivise; 263 | assert_eq!(positivise(&recovered_secrets, pss.prime), secrets); 264 | } 265 | 266 | #[test] 267 | fn test_large_share() { 268 | let ref pss = PSS_155_19682_100; 269 | let secrets = vec![5 ; pss.secret_count]; 270 | let shares = pss.share(&secrets); 271 | assert_eq!(shares.len(), pss.share_count); 272 | } 273 | 274 | #[test] 275 | fn test_share_reconstruct() { 276 | let ref pss = PSS_4_26_3; 277 | let secrets = vec![5, 6, 7]; 278 | let shares = pss.share(&secrets); 279 | 280 | use numtheory::positivise; 281 | 282 | // reconstruction must work for all shares 283 | let indices: Vec = (0..shares.len()).collect(); 284 | let recovered_secrets = pss.reconstruct(&indices, &shares); 285 | assert_eq!(positivise(&recovered_secrets, pss.prime), secrets); 286 | 287 | // .. and for only sufficient shares 288 | let indices: Vec = (0..pss.reconstruct_limit()).collect(); 289 | let recovered_secrets = pss.reconstruct(&indices, &shares[0..pss.reconstruct_limit()]); 290 | print!("lenght is {:?}", indices.len()); 291 | assert_eq!(positivise(&recovered_secrets, pss.prime), secrets); 292 | } 293 | 294 | #[test] 295 | fn test_share_additive_homomorphism() { 296 | let ref pss = PSS_4_26_3; 297 | 298 | let secrets_1 = vec![1, 2, 3]; 299 | let secrets_2 = vec![4, 5, 6]; 300 | let shares_1 = pss.share(&secrets_1); 301 | let shares_2 = pss.share(&secrets_2); 302 | 303 | // add shares pointwise 304 | let shares_sum: Vec = 305 | shares_1.iter().zip(shares_2).map(|(a, b)| (a + b) % pss.prime).collect(); 306 | 307 | // reconstruct sum, using same reconstruction limit 308 | let reconstruct_limit = pss.reconstruct_limit(); 309 | let indices: Vec = (0..reconstruct_limit).collect(); 310 | let shares = &shares_sum[0..reconstruct_limit]; 311 | let recovered_secrets = pss.reconstruct(&indices, shares); 312 | 313 | use numtheory::positivise; 314 | assert_eq!(positivise(&recovered_secrets, pss.prime), vec![5, 7, 9]); 315 | } 316 | 317 | #[test] 318 | fn test_share_multiplicative_homomorphism() { 319 | let ref pss = PSS_4_26_3; 320 | 321 | let secrets_1 = vec![1, 2, 3]; 322 | let secrets_2 = vec![4, 5, 6]; 323 | let shares_1 = pss.share(&secrets_1); 324 | let shares_2 = pss.share(&secrets_2); 325 | 326 | // multiply shares pointwise 327 | let shares_product: Vec = 328 | shares_1.iter().zip(shares_2).map(|(a, b)| (a * b) % pss.prime).collect(); 329 | 330 | // reconstruct product, using double reconstruction limit 331 | let reconstruct_limit = pss.reconstruct_limit() * 2; 332 | let indices: Vec = (0..reconstruct_limit).collect(); 333 | let shares = &shares_product[0..reconstruct_limit]; 334 | let recovered_secrets = pss.reconstruct(&indices, shares); 335 | 336 | use numtheory::positivise; 337 | assert_eq!(positivise(&recovered_secrets, pss.prime), vec![4, 10, 18]); 338 | } 339 | 340 | } 341 | 342 | 343 | #[doc(hidden)] 344 | #[cfg(feature = "paramgen")] 345 | pub mod paramgen { 346 | 347 | //! Optional helper methods for parameter generation 348 | 349 | extern crate primal; 350 | 351 | #[cfg_attr(rustfmt, rustfmt_skip)] 352 | fn check_prime_form(min_p: usize, n: usize, m: usize, p: usize) -> bool { 353 | if p < min_p { return false; } 354 | 355 | let q = p - 1; 356 | if q % n != 0 { return false; } 357 | if q % m != 0 { return false; } 358 | 359 | let q = q / (n * m); 360 | if q % n == 0 { return false; } 361 | if q % m == 0 { return false; } 362 | 363 | return true; 364 | } 365 | 366 | #[test] 367 | fn test_check_prime_form() { 368 | assert_eq!(primal::Primes::all().find(|p| check_prime_form(198, 8, 9, *p)).unwrap(), 433); 369 | } 370 | 371 | fn factor(p: usize) -> Vec { 372 | let mut factors = vec![]; 373 | let bound = (p as f64).sqrt().ceil() as usize; 374 | for f in 2..bound + 1 { 375 | if p % f == 0 { 376 | factors.push(f); 377 | factors.push(p / f); 378 | } 379 | } 380 | factors 381 | } 382 | 383 | #[test] 384 | fn test_factor() { 385 | assert_eq!(factor(40), [2, 20, 4, 10, 5, 8]); 386 | assert_eq!(factor(41), []); 387 | } 388 | 389 | fn find_field(min_p: usize, n: usize, m: usize) -> Option<(i64, i64)> { 390 | // find prime of right form 391 | let p = primal::Primes::all().find(|p| check_prime_form(min_p, n, m, *p)).unwrap(); 392 | // find (any) generator 393 | let factors = factor(p - 1); 394 | for g in 2..p { 395 | // test generator against all factors of p-1 396 | let is_generator = factors.iter().all(|f| { 397 | use numtheory::mod_pow; 398 | let e = (p - 1) / f; 399 | mod_pow(g as i64, e as u32, p as i64) != 1 // TODO check for negative value 400 | }); 401 | // return 402 | if is_generator { 403 | return Some((p as i64, g as i64)); 404 | } 405 | } 406 | // didn't find any 407 | None 408 | } 409 | 410 | #[test] 411 | fn test_find_field() { 412 | assert_eq!(find_field(198, 2usize.pow(3), 3usize.pow(2)).unwrap(), 413 | (433, 5)); 414 | assert_eq!(find_field(198, 2usize.pow(3), 3usize.pow(3)).unwrap(), 415 | (433, 5)); 416 | assert_eq!(find_field(198, 2usize.pow(8), 3usize.pow(6)).unwrap(), 417 | (746497, 5)); 418 | assert_eq!(find_field(198, 2usize.pow(8), 3usize.pow(9)).unwrap(), 419 | (5038849, 29)); 420 | 421 | // assert_eq!(find_field(198, 2usize.pow(11), 3usize.pow(8)).unwrap(), (120932353, 5)); 422 | // assert_eq!(find_field(198, 2usize.pow(13), 3usize.pow(9)).unwrap(), (483729409, 23)); 423 | } 424 | 425 | fn find_roots(n: usize, m: usize, p: i64, g: i64) -> (i64, i64) { 426 | use numtheory::mod_pow; 427 | let omega_secrets = mod_pow(g, ((p - 1) / n as i64) as u32, p); 428 | let omega_shares = mod_pow(g, ((p - 1) / m as i64) as u32, p); 429 | (omega_secrets, omega_shares) 430 | } 431 | 432 | #[test] 433 | fn test_find_roots() { 434 | assert_eq!(find_roots(2usize.pow(3), 3usize.pow(2), 433, 5), (354, 150)); 435 | assert_eq!(find_roots(2usize.pow(3), 3usize.pow(3), 433, 5), (354, 17)); 436 | } 437 | 438 | #[doc(hidden)] 439 | pub fn generate_parameters(min_size: usize, n: usize, m: usize) -> (i64, i64, i64) { 440 | // TODO settle option business once and for all (don't remember it as needed) 441 | let (prime, g) = find_field(min_size, n, m).unwrap(); 442 | let (omega_secrets, omega_shares) = find_roots(n, m, prime, g); 443 | (prime, omega_secrets, omega_shares) 444 | } 445 | 446 | #[test] 447 | fn test_generate_parameters() { 448 | assert_eq!(generate_parameters(200, 2usize.pow(3), 3usize.pow(2)), 449 | (433, 354, 150)); 450 | assert_eq!(generate_parameters(200, 2usize.pow(3), 3usize.pow(3)), 451 | (433, 354, 17)); 452 | } 453 | 454 | fn is_power_of(x: usize, e: usize) -> bool { 455 | let power = (x as f64).log(e as f64).floor() as u32; 456 | e.pow(power) == x 457 | } 458 | 459 | #[test] 460 | fn test_is_power_of() { 461 | assert_eq!(is_power_of(4, 2), true); 462 | assert_eq!(is_power_of(5, 2), false); 463 | assert_eq!(is_power_of(6, 2), false); 464 | assert_eq!(is_power_of(7, 2), false); 465 | assert_eq!(is_power_of(8, 2), true); 466 | 467 | assert_eq!(is_power_of(4, 3), false); 468 | assert_eq!(is_power_of(5, 3), false); 469 | assert_eq!(is_power_of(6, 3), false); 470 | assert_eq!(is_power_of(7, 3), false); 471 | assert_eq!(is_power_of(8, 3), false); 472 | assert_eq!(is_power_of(9, 3), true); 473 | } 474 | 475 | use super::PackedSecretSharing; 476 | 477 | impl PackedSecretSharing { 478 | 479 | /// Find suitable parameters with as small a prime field as possible. 480 | pub fn new(threshold: usize, 481 | secret_count: usize, 482 | share_count: usize) 483 | -> PackedSecretSharing { 484 | let min_size = share_count + secret_count + threshold + 1; 485 | Self::new_with_min_size(threshold, secret_count, share_count, min_size) 486 | } 487 | 488 | /// Find suitable parameters with a prime field of at least the specified size. 489 | pub fn new_with_min_size(threshold: usize, 490 | secret_count: usize, 491 | share_count: usize, 492 | min_size: usize) 493 | -> PackedSecretSharing { 494 | 495 | let m = threshold + secret_count + 1; 496 | let n = share_count + 1; 497 | assert!(is_power_of(m, 2)); 498 | assert!(is_power_of(n, 3)); 499 | assert!(min_size >= share_count + secret_count + threshold + 1); 500 | 501 | let (prime, omega_secrets, omega_shares) = generate_parameters(min_size, m, n); 502 | 503 | PackedSecretSharing { 504 | threshold: threshold, 505 | share_count: share_count, 506 | secret_count: secret_count, 507 | prime: prime, 508 | omega_secrets: omega_secrets, 509 | omega_shares: omega_shares, 510 | } 511 | } 512 | } 513 | 514 | #[test] 515 | fn test_new() { 516 | assert_eq!(PackedSecretSharing::new(155, 100, 728), 517 | super::PSS_155_728_100); 518 | assert_eq!(PackedSecretSharing::new_with_min_size(4, 3, 8, 200), 519 | super::PSS_4_8_3); 520 | assert_eq!(PackedSecretSharing::new_with_min_size(4, 3, 26, 200), 521 | super::PSS_4_26_3); 522 | } 523 | 524 | } 525 | --------------------------------------------------------------------------------