Implement challenge 34

This commit is contained in:
2022-09-02 12:28:57 -04:00
parent 9e568ac97c
commit ad3a292e0e
3 changed files with 224 additions and 35 deletions

View File

@@ -1,12 +1,26 @@
pub fn expmod(base: u32, exp: u32, m: u32) -> u32 {
if exp == 0 {
return 1;
}
use num_bigint::BigUint;
use num_bigint::RandBigInt;
if exp % 2 == 0 {
let s = expmod(base, exp / 2, m);
(s * s) % m
} else {
(expmod(base, exp - 1, m) * base) % m
#[derive(Clone)]
pub struct PublicKey(pub BigUint);
#[derive(Clone)]
pub struct PrivateKey(pub BigUint);
#[derive(Clone)]
pub struct Keypair {
pub private: PrivateKey,
pub public: PublicKey,
}
impl Keypair {
pub fn make(p: &BigUint, g: &BigUint) -> Self {
let mut rng = rand::thread_rng();
let private = rng.gen_biguint_below(p);
let public = g.modpow(&private, p);
Self {
private: PrivateKey(private),
public: PublicKey(public),
}
}
}