Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,23 @@ edition = "2021"

[dependencies]
core2 = "0.4"
num-bigint = { version = "0.4", features = ["rand"] }
num-bigint = { version = "0.5", features = ["rand"] }
num-traits = "0.2"
num-integer = "0.1"
rand_core = { version = "0.6", features = ["getrandom"] }
rand_core = { version = "0.9", features = ["os_rng"] }
once_cell = "1.17"

[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
rand = "0.8"
rand = "0.9"

[[bench]]
name = "gen_safe_prime"
harness = false

[profile.bench]
opt-level = 3

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious why this is needed

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because this pulls the PR that bumps num-bigint to rand_core 0.9.0.

rust-num/num-bigint#317

we can keep this one open until we get the upstream one merged if you prefer.

[patch.crates-io]
# https://github.com/rust-num/num-bigint/pull/317
num-bigint = { git = "https://github.com/bionicles/num-bigint.git" }
12 changes: 6 additions & 6 deletions src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ fn _is_prime<R: RngCore + ?Sized>(
/// Generate a random candidate uint of the requested bit length
#[inline]
fn _prime_candidate<R: RngCore + ?Sized>(bit_length: u64, rng: &mut R) -> BigUint {
let mut candidate = rng.gen_biguint(bit_length);
let mut candidate = rng.random_biguint(bit_length);

// Set lowest bit (ensure odd)
candidate.set_bit(0, true);
Expand Down Expand Up @@ -213,7 +213,7 @@ fn required_checks(bits: usize) -> usize {
/// primality.
#[inline]
fn fermat<R: RngCore + ?Sized>(candidate: &BigUint, rng: &mut R) -> bool {
let random = rng.gen_biguint_range(&BigUint::one(), candidate);
let random = rng.random_biguint_range(&BigUint::one(), candidate);

let result = random.modpow(&(candidate - 1_u8), candidate);

Expand Down Expand Up @@ -640,11 +640,11 @@ mod tests {
use crate::error::Error;
use num_bigint::BigUint;
use num_traits::Num;
use rand::thread_rng;
use rand::rng;

#[test]
fn gen_safe_prime_tests() {
let mut rng = thread_rng();
let mut rng = rng();
match gen_prime(16, &mut rng) {
Ok(_) => panic!("No primes allowed under 16 bits"),
Err(e) => match e {
Expand All @@ -662,7 +662,7 @@ mod tests {

#[test]
fn gen_prime_tests() {
let mut rng = thread_rng();
let mut rng = rng();
match gen_prime(16, &mut rng) {
Ok(_) => panic!("No primes allowed under 16 bits"),
Err(e) => match e {
Expand All @@ -680,7 +680,7 @@ mod tests {

#[test]
fn is_prime_tests() {
let mut rng = thread_rng();
let mut rng = rng();
for prime in PRIMES.iter().copied() {
assert!(is_prime(&BigUint::from(prime), &mut rng));
}
Expand Down
19 changes: 11 additions & 8 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,20 @@ pub type Result = result::Result<num_bigint::BigUint, Error>;
#[derive(Debug)]
pub enum Error {
/// Handles when the OS Rng fails to initialize
OsRngInitialization(rand_core::Error),
OsRngInitialization,
/// Handles when the bit sizes are too small
BitLength(usize),
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::OsRngInitialization(ref err) => {
write!(f, "Error initializing OS random number generator: {}", err)
Error::OsRngInitialization => {
write!(f, "Error initializing OS random number generator")
}
//Error::OsRngInitialization(ref err) => {
// write!(f, "Error initializing OS random number generator: {}", err)
//}
Error::BitLength(length) => write!(
f,
"The given bit length is too small; must be at least {}: {}",
Expand All @@ -33,8 +36,8 @@ impl fmt::Display for Error {

impl error::Error for Error {}

impl From<rand_core::Error> for Error {
fn from(err: rand_core::Error) -> Error {
Error::OsRngInitialization(err)
}
}
//impl From<rand_core::Error> for Error {
// fn from(err: rand_core::Error) -> Error {
// Error::OsRngInitialization(err)
// }
//}
8 changes: 4 additions & 4 deletions src/prime.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Generates cryptographically secure prime numbers.

use rand_core::OsRng;
use rand_core::{OsRng, TryRngCore};

pub use crate::common::{
gen_prime as from_rng, is_prime as check_with, is_prime_baillie_psw as strong_check_with,
Expand All @@ -14,7 +14,7 @@ use crate::error::Result;
///
/// Note: the `bit_length` MUST be at least 128-bits.
pub fn new(bit_length: usize) -> Result {
from_rng(bit_length, &mut OsRng)
from_rng(bit_length, &mut OsRng.unwrap_err())
}

/// Test if number is prime by
Expand All @@ -24,12 +24,12 @@ pub fn new(bit_length: usize) -> Result {
/// 3- Perform log2(bitlength) + 5 rounds of Miller-Rabin
/// depending on the number of bits
pub fn check(candidate: &num_bigint::BigUint) -> bool {
check_with(candidate, &mut OsRng)
check_with(candidate, &mut OsRng.unwrap_err())
}

/// Checks if number is a prime using the Baillie-PSW test
pub fn strong_check(candidate: &num_bigint::BigUint) -> bool {
strong_check_with(candidate, &mut OsRng)
strong_check_with(candidate, &mut OsRng.unwrap_err())
}

#[cfg(test)]
Expand Down
8 changes: 4 additions & 4 deletions src/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl<R: RngCore> Randoms<R> {

fn gen_biguint(&mut self) -> BigUint {
self.rng
.gen_biguint_range(&self.lower_limit, &self.upper_limit)
.random_biguint_range(&self.lower_limit, &self.upper_limit)
}
}

Expand All @@ -60,17 +60,17 @@ impl<R: RngCore> Iterator for Randoms<R> {
#[cfg(test)]
mod test {
use super::Randoms;
use rand::thread_rng;
use rand::rng;

#[test]
fn generate_amount_test() {
let amount = 3;
let rands = Randoms::new(0_u8.into(), 1_u8.into(), amount, thread_rng());
let rands = Randoms::new(0_u8.into(), 1_u8.into(), amount, rng());
let generated = rands.collect::<Vec<_>>();
assert_eq!(generated.len(), amount);

let rands =
Randoms::new(0_u8.into(), 1_u8.into(), amount, thread_rng()).with_appended(2_u8.into());
Randoms::new(0_u8.into(), 1_u8.into(), amount, rng()).with_appended(2_u8.into());
let generated = rands.collect::<Vec<_>>();
assert_eq!(generated.len(), amount);
}
Expand Down
8 changes: 4 additions & 4 deletions src/safe_prime.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Generates cryptographically secure safe prime numbers.

use rand_core::OsRng;
use rand_core::{OsRng, TryRngCore};

pub use crate::common::{
gen_safe_prime as from_rng, is_safe_prime as check_with,
Expand All @@ -15,17 +15,17 @@ use crate::error::Result;
///
/// Note: the `bit_length` MUST be at least 128-bits.
pub fn new(bit_length: usize) -> Result {
from_rng(bit_length, &mut OsRng)
from_rng(bit_length, &mut OsRng.unwrap_err())
}

/// Checks if number is a safe prime
pub fn check(candidate: &num_bigint::BigUint) -> bool {
check_with(candidate, &mut OsRng)
check_with(candidate, &mut OsRng.unwrap_err())
}

/// Checks if number is a safe prime using the Baillie-PSW test
pub fn strong_check(candidate: &num_bigint::BigUint) -> bool {
strong_check_with(candidate, &mut OsRng)
strong_check_with(candidate, &mut OsRng.unwrap_err())
}

#[cfg(test)]
Expand Down