Skip to content

Commit

Permalink
Better prime number generation
Browse files Browse the repository at this point in the history
  • Loading branch information
hauleth committed Sep 16, 2015
1 parent e75f6bd commit d8b4248
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
4 changes: 2 additions & 2 deletions src/crypto/public_key/rsa/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ impl Key {

pub fn generate_keypair<G, T>(mut rng: G, e: T, bits: usize) -> KeyPair
where G: Rng + RandBigInt, T: Into<BigUint> {
let p = generate_prime(&mut rng, bits);
let q = generate_prime(&mut rng, bits);
let p = generate_prime(&mut rng, bits).expect("Cannot generate safe prime");
let q = generate_prime(&mut rng, bits).expect("Cannot generate safe prime");

Self::keypair_from_primes(p, q, e)
}
Expand Down
16 changes: 13 additions & 3 deletions src/utils/primes/mod.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
use num::{One, Integer};
use num::bigint::{BigUint, RandBigInt};
use rand::Rng;

use utils::primes::tests::PrimeTest;

pub mod tests;

pub fn generate_prime<T: Rng + RandBigInt>(gen: &mut T, bits: usize) -> BigUint {
/// Generate new prime number with given bit size via given random number generator.
///
/// Currently this function give guarantee that it ever ends. In case of bad `Rng` engine
/// this could fall into endless loop.
///
/// This function doesn't reseed `Rng` so You must provide autoreseedable engine, check out
/// [`ReseedingRng`](http://doc.rust-lang.org/rand/rand/reseeding/struct.ReseedingRng.html).
pub fn generate_prime<T: Rng + RandBigInt>(gen: &mut T, bits: usize) -> Option<BigUint> {
loop {
let int = gen.gen_biguint(bits);
let mut int = gen.gen_biguint(bits);

if int.is_even() { int = int + BigUint::one(); }

if tests::Fermat(gen).test_loop(&int, 50).is_composite() { continue }
if tests::MillerRabin(gen).test_loop(&int, 50).is_composite() { continue }

return int
return Some(int)
}
}

0 comments on commit d8b4248

Please sign in to comment.