From 7c97a02804135a582b50b588ed134464b7567df6 Mon Sep 17 00:00:00 2001 From: mgostIH Date: Thu, 2 Jul 2020 11:12:05 +0200 Subject: [PATCH 1/2] Removed bigint dependency and changed RSA algorithm to use u128 --- Cargo.toml | 7 +------ src/cb7.rs | 38 +++++++++++++++++++++++++++++++------- 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c0b2305..dcd7b9b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,9 +16,4 @@ edition = "2018" name = "codebreaker" [dependencies] -bytemuck = "1.2" -num-bigint = "0.3" - -[features] -default = ["std"] -std = ["num-bigint/std"] +bytemuck = "1.2" \ No newline at end of file diff --git a/src/cb7.rs b/src/cb7.rs index 0c4e404..bac3d6f 100644 --- a/src/cb7.rs +++ b/src/cb7.rs @@ -303,16 +303,40 @@ const fn mod_inverse(x: u32) -> u32 { // RSA encryption/decryption fn rsa_crypt(addr: &mut u32, val: &mut u32, rsakey: u64, modulus: u64) { - use num_bigint::BigUint; + // Code directly copy pasted from Rust's std, with addition of % modulus + pub fn mod_pow(base : u64, exp: u64, modulus : u64) -> u64 { + let mut base = base as u128; + let mut exp = exp as u128; + let modulus = modulus as u128; + let mut acc = 1; + + while exp > 1 { + if (exp & 1) == 1 { + acc = acc * base; + acc %= modulus; + } + exp /= 2; + base = base * base; + base %= modulus; + } - let code = BigUint::from_slice(&[*val, *addr]); - let m = BigUint::from(modulus); + // Deal with the final bit of the exponent separately, since + // squaring the base afterwards is not necessary and may cause a + // needless overflow. + if exp == 1 { + acc = acc * base; + } + + (acc % modulus) as u64 + } + + let code = (*addr as u64) << 32 | (*val as u64); // Exponentiation is only invertible if code < modulus - if code < m { - let digits = code.modpow(&BigUint::from(rsakey), &m).to_u32_digits(); - *addr = digits[1]; - *val = digits[0]; + if code < modulus { + let digits = mod_pow(code, rsakey, modulus); + *addr = (digits >> 32) as u32; + *val = digits as u32; } } From b8fd3fb02a9d3bbc22c32df37620a7f30c1662e9 Mon Sep 17 00:00:00 2001 From: mgostIH Date: Thu, 2 Jul 2020 11:22:23 +0200 Subject: [PATCH 2/2] Fixed lints --- src/cb7.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cb7.rs b/src/cb7.rs index bac3d6f..822d15e 100644 --- a/src/cb7.rs +++ b/src/cb7.rs @@ -312,7 +312,7 @@ fn rsa_crypt(addr: &mut u32, val: &mut u32, rsakey: u64, modulus: u64) { while exp > 1 { if (exp & 1) == 1 { - acc = acc * base; + acc *= base; acc %= modulus; } exp /= 2; @@ -324,7 +324,7 @@ fn rsa_crypt(addr: &mut u32, val: &mut u32, rsakey: u64, modulus: u64) { // squaring the base afterwards is not necessary and may cause a // needless overflow. if exp == 1 { - acc = acc * base; + acc *= base; } (acc % modulus) as u64