From 596adf5d3243975aa719e897d02db93da28709c8 Mon Sep 17 00:00:00 2001 From: jacekpoz Date: Tue, 14 May 2024 15:03:12 +0200 Subject: [PATCH] improve printing and actually find the private key --- l4/z1/rsa-rs/src/main.rs | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/l4/z1/rsa-rs/src/main.rs b/l4/z1/rsa-rs/src/main.rs index 7fda804..7bf0a07 100644 --- a/l4/z1/rsa-rs/src/main.rs +++ b/l4/z1/rsa-rs/src/main.rs @@ -114,7 +114,7 @@ fn pow_mod(a: &BigUint, exp: &BigUint, n: &BigUint) -> BigUint { res } -fn find_private_key(n: &BigUint, e: &BigUint, d: &BigUint) -> (BigUint, BigUint) { +fn find_primes(n: &BigUint, e: &BigUint, d: &BigUint) -> (BigUint, BigUint) { let kphi = d * e - 1u32; let mut t = kphi.clone(); while &t % 2u32 == BigUint::zero() { @@ -145,6 +145,14 @@ fn find_private_key(n: &BigUint, e: &BigUint, d: &BigUint) -> (BigUint, BigUint) (p, q) } +fn find_private_key(p1: &BigUint, p2: &BigUint, e: &BigUint) -> BigUint { + let phi = (p1 - 1u32) * (p2 - 1u32); + + let d = euclid(e, &phi); + + d +} + fn main() { let n = env::args().nth(1) .expect(format!("usage: {} ", env::args().nth(0).unwrap()).as_str()) @@ -152,25 +160,38 @@ fn main() { .expect("key length must be usize"); let p1: BigUint = thread_rng().gen_prime_exact(n, Some(PrimalityTestConfig::strict())); - println!("p1 ({b} bits): {p1}", b = p1.bits()); + println!("p1 ({b} bits): 0x{p1:X}", b = p1.bits()); let p2: BigUint = thread_rng().gen_prime_exact(n, Some(PrimalityTestConfig::strict())); - println!("p2 ({b} bits): {p2}", b = p1.bits()); + println!("p2 ({b} bits): 0x{p2:X}", b = p1.bits()); + + println!(); let pair_a = generate_key_pair(&p1, &p2) .expect("failed to generate key pair a"); println!("private key A: {}", pair_a.private); println!("public key A: {}", pair_a.public); + println!(); + let pair_b = generate_key_pair(&p1, &p2) .expect("failed to generate key pair b"); println!("private key B: {}", pair_b.private); println!("public key B: {}", pair_b.public); - let found_secret = find_private_key(&pair_a.public.n, &pair_a.public.key, &pair_a.private.key); - println!("found_b: (0x{:X}, 0x{:X})", found_secret.0, found_secret.1); - if (&found_secret.0 == &p1 && &found_secret.1 == &p2) - || (&found_secret.0 == &p2 && &found_secret.1 == &p1) { + println!(); + + let found_primes = find_primes(&pair_a.public.n, &pair_a.public.key, &pair_a.private.key); + println!("found_primes: (0x{:X}, 0x{:X})", found_primes.0, found_primes.1); + + println!(); + + let found_private_key = find_private_key(&found_primes.0, &found_primes.1, &pair_b.public.key); + println!("found_private_key: 0x{:X}", found_private_key); + + println!(); + + if found_private_key == pair_b.private.key { println!("cracked B)"); } else { println!("uncracked B(");