Implemented `Rand` for `SecretKey`.

This commit is contained in:
Marc Brinkmann 2018-07-04 16:43:17 +02:00 committed by Vladimir Komendantskiy
parent 51b87b8bae
commit b7d12585f8
1 changed files with 12 additions and 13 deletions

25
mod.rs
View File

@ -16,7 +16,7 @@ use clear_on_drop::ClearOnDrop;
use init_with::InitWith; use init_with::InitWith;
use pairing::bls12_381::{Bls12, Fr, FrRepr, G1, G1Affine, G2, G2Affine}; use pairing::bls12_381::{Bls12, Fr, FrRepr, G1, G1Affine, G2, G2Affine};
use pairing::{CurveAffine, CurveProjective, Engine, Field, PrimeField}; use pairing::{CurveAffine, CurveProjective, Engine, Field, PrimeField};
use rand::{ChaChaRng, OsRng, Rng, SeedableRng}; use rand::{ChaChaRng, OsRng, Rand, Rng, SeedableRng};
use ring::digest; use ring::digest;
use self::error::{ErrorKind, Result}; use self::error::{ErrorKind, Result};
@ -129,12 +129,14 @@ impl Default for SecretKey {
} }
} }
impl SecretKey { impl Rand for SecretKey {
/// Creates a new secret key. fn rand<R: Rng>(rng: &mut R) -> Self {
pub fn new<R: Rng>(rng: &mut R) -> Self {
SecretKey(rng.gen()) SecretKey(rng.gen())
} }
}
impl SecretKey {
/// Creates a secret key from an existing value
pub fn from_value(f: Fr) -> Self { pub fn from_value(f: Fr) -> Self {
SecretKey(f) SecretKey(f)
} }
@ -405,13 +407,12 @@ mod tests {
use std::collections::BTreeMap; use std::collections::BTreeMap;
use rand; use rand::{self, random};
#[test] #[test]
fn test_simple_sig() { fn test_simple_sig() {
let mut rng = rand::thread_rng(); let sk0: SecretKey = random();
let sk0 = SecretKey::new(&mut rng); let sk1: SecretKey = random();
let sk1 = SecretKey::new(&mut rng);
let pk0 = sk0.public_key(); let pk0 = sk0.public_key();
let msg0 = b"Real news"; let msg0 = b"Real news";
let msg1 = b"Fake news"; let msg1 = b"Fake news";
@ -464,9 +465,8 @@ mod tests {
#[test] #[test]
fn test_simple_enc() { fn test_simple_enc() {
let mut rng = rand::thread_rng(); let sk_bob: SecretKey = random();
let sk_bob = SecretKey::new(&mut rng); let sk_eve: SecretKey = random();
let sk_eve = SecretKey::new(&mut rng);
let pk_bob = sk_bob.public_key(); let pk_bob = sk_bob.public_key();
let msg = b"Muffins in the canteen today! Don't tell Eve!"; let msg = b"Muffins in the canteen today! Don't tell Eve!";
let ciphertext = pk_bob.encrypt(&msg[..]); let ciphertext = pk_bob.encrypt(&msg[..]);
@ -566,8 +566,7 @@ mod tests {
fn test_serde() { fn test_serde() {
use bincode; use bincode;
let mut rng = rand::thread_rng(); let sk: SecretKey = random();
let sk = SecretKey::new(&mut rng);
let sig = sk.sign("Please sign here: ______"); let sig = sk.sign("Please sign here: ______");
let pk = sk.public_key(); let pk = sk.public_key();
let ser_pk = bincode::serialize(&pk).expect("serialize public key"); let ser_pk = bincode::serialize(&pk).expect("serialize public key");