|
| 1 | +extern crate rand; |
| 2 | +use std::io::{self, Write}; |
| 3 | + |
| 4 | +fn mod_exp(base: u64, exp: u64, modulus: u64) -> u64 { |
| 5 | + let mut result = 1; |
| 6 | + let mut base = base % modulus; |
| 7 | + let mut exp = exp; |
| 8 | + |
| 9 | + while exp > 0 { |
| 10 | + if exp % 2 == 1 { |
| 11 | + result = (result * base) % modulus; |
| 12 | + } |
| 13 | + exp = exp >> 1; |
| 14 | + base = (base * base) % modulus; |
| 15 | + } |
| 16 | + result |
| 17 | +} |
| 18 | + |
| 19 | +fn read_input(prompt: &str) -> u64 { |
| 20 | + print!("{}", prompt); |
| 21 | + io::stdout().flush().unwrap(); // Ensure prompt is printed before reading |
| 22 | + let mut input = String::new(); |
| 23 | + io::stdin().read_line(&mut input).unwrap(); |
| 24 | + input.trim().parse().unwrap() |
| 25 | +} |
| 26 | + |
| 27 | +fn main() { |
| 28 | + // Get the prime number (p) and base (g) from user input |
| 29 | + let p = read_input("Enter a prime number (p): "); |
| 30 | + let g = read_input("Enter the base (g): "); |
| 31 | + |
| 32 | + // Get private keys for Alice and Bob |
| 33 | + let a = read_input("Enter Alice's private key: "); |
| 34 | + let b = read_input("Enter Bob's private key: "); |
| 35 | + |
| 36 | + // Compute the public keys |
| 37 | + let avar = mod_exp(g, a, p); // Alice's public key |
| 38 | + let bvar = mod_exp(g, b, p); // Bob's public key |
| 39 | + |
| 40 | + println!("\nPrime number (p): {}", p); |
| 41 | + println!("Base (g): {}", g); |
| 42 | + println!("Alice's private key: {}", a); |
| 43 | + println!("Bob's private key: {}", b); |
| 44 | + println!("Alice's public key: {}", avar); |
| 45 | + println!("Bob's public key: {}", bvar); |
| 46 | + |
| 47 | + // Exchange public keys (this is done securely in a real-world scenario) |
| 48 | + println!("\nExchanging public keys..."); |
| 49 | + |
| 50 | + // Alice computes the shared secret using Bob's public key |
| 51 | + let shared_secret_alice = mod_exp(bvar, a, p); |
| 52 | + // Bob computes the shared secret using Alice's public key |
| 53 | + let shared_secret_bob = mod_exp(avar, b, p); |
| 54 | + |
| 55 | + println!("\nAlice's computed shared secret: {}", shared_secret_alice); |
| 56 | + println!("Bob's computed shared secret: {}", shared_secret_bob); |
| 57 | + |
| 58 | + // Verify that the shared secrets are the same |
| 59 | + if shared_secret_alice == shared_secret_bob { |
| 60 | + println!("\nThe shared secret is the same! Key exchange successful."); |
| 61 | + } else { |
| 62 | + println!("\nThe shared secrets do not match. Something went wrong."); |
| 63 | + } |
| 64 | +} |
0 commit comments