Implement challenge 34
This commit is contained in:
32
src/rsa.rs
32
src/rsa.rs
@@ -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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user