rsa_rust/helpers/
generics.rs

1//! Generic_Helpers
2use crate::types::*;
3use num_bigint::{BigUint, BigInt};
4use num::{Zero, One, Signed};
5use std::str::FromStr;
6use base64::*;
7use std::str::from_utf8;
8use std::fs::File;
9use std::io::{BufRead, BufReader};
10
11
12/// Formats a BigUint ready to be written on a file.
13macro_rules! encode_to_print {
14    ($big_num: expr) => {
15        encode(&$big_num.to_radix_be(16u32)).as_bytes()
16    };
17}
18
19#[cfg(test)]
20#[test]
21fn encodes_to_print() {
22    let known_prime_str =
23    "118595363679537468261258276757550704318651155601593299292198496313960907653004730006758459999825003212944725610469590674020124506249770566394260832237809252494505683255861199449482385196474342481641301503121142740933186279111209376061535491003888763334916103110474472949854230628809878558752830476310536476569";
24    let known_prime: BigUint = FromStr::from_str(known_prime_str).unwrap();
25    let expected = "CggOAgoJDQMBBAMEAgwKAwgABAwLBwAIDgEPBQYMDAEDDQ0BCQ0HDgoJDA0EBwMKCwkBBgQOAA4CAgsABAgOCwwDAwMDAQYLBgMBDwIIAwUAAwsEAwgGCg0BAwcFCwsBCgsKCQkACA0NDwYCCAgKDwALCgUODQcDCgoCAQYNCgsDCgAGCgoKAAQDCgcFBgsJCAADBw8KCAUACA4GCQgEDQsNBwkPCQcKDw4MDgQBCAICCwEEDwEBCggPBwEEDQMMBAMCCAgPBgQDDAQJCgwBCAMIAAkCDAUAAwIJDwsECAgOCwwGBgQGBQELCgoEAwINDAoPDAUDDA0DCAYHBQcJCQ==";
26    assert_eq!(expected, from_utf8(encode_to_print!(&known_prime)).unwrap());
27    
28}
29
30
31/// Generates 0, 1 and 2 numbers as BigUint
32pub fn gen_basic_biguints() -> (BigUint, BigUint, BigUint) {
33    (BigUint::zero(), BigUint::one(), BigUint::one() + BigUint::one())
34}
35
36/// Generates 0, 1 and 2 numbers as BigUint
37pub fn gen_basic_bigints() -> (BigInt, BigInt, BigInt) {
38    (BigInt::zero(), BigInt::one(), BigInt::one() + BigInt::one())
39}
40
41/// Generate a BigUint from a positive BigInt
42pub fn biguint_from_bigint(a: &BigInt) -> Result<BigUint, &'static str> {
43    if a.is_negative() {return Err("Error converting a negative BigInt to a BigUint")}
44    let boxed = format!("{}", a.clone()).into_boxed_str();
45    let biguint_str = Box::leak(boxed);
46    Ok(BigUint::from_str(biguint_str).unwrap())
47}
48
49// Format Keypair to print it on a file.
50pub fn prepare_to_print(kp: &KeyPair) -> Result<(String, String), &'static str> {
51    let (mut encoded_pk, mut encoded_sk) = (String::new(), String::new());
52    // Encoding Public Key
53    encoded_pk.push_str("---------- BEGIN RSA PUBLIC KEY ----------");
54    encoded_pk.push_str("\n");
55    encoded_pk.push_str(from_utf8(encode_to_print!(&kp.pk.n)).unwrap());
56    encoded_pk.push_str("\n");
57    encoded_pk.push_str(from_utf8(encode_to_print!(&kp.pk.e)).unwrap());
58    encoded_pk.push_str("\n");
59    encoded_pk.push_str("----------- END RSA PUBLIC KEY -----------");
60    encoded_pk.push_str("\n");
61    encoded_pk.push_str(&kp.size.to_string());
62    encoded_pk.push_str("\n");
63    encoded_pk.push_str(&kp.threshold.to_string());
64    
65    // Encoding Secret Key
66    encoded_sk.push_str("---------- BEGIN RSA PRIVATE KEY ----------");
67    encoded_sk.push_str("\n");
68    encoded_sk.push_str(from_utf8(encode_to_print!(&kp.sk.n)).unwrap());
69    encoded_sk.push_str("\n");
70    encoded_sk.push_str(from_utf8(encode_to_print!(&kp.sk.d)).unwrap());
71    encoded_sk.push_str("\n");
72    encoded_sk.push_str("----------- END RSA PRIVATE KEY -----------");
73    encoded_sk.push_str("\n");
74    encoded_sk.push_str(&kp.size.to_string());
75    encoded_sk.push_str("\n");
76    encoded_sk.push_str(&kp.threshold.to_string());
77    Ok((encoded_pk, encoded_sk))
78}
79
80/// Gets Public Key params from the Pk file.
81/// Returns a Public Key Struct or an Error.
82pub fn get_pk_params(pk_file: &File) -> Result<PublicKey, &'static str> {
83    let mut lines = vec!();
84    for line in BufReader::new(pk_file).lines() {
85        lines.push(line)
86    }
87    let pk = PublicKey::new(
88    &BigUint::from_radix_be(from_utf8(&base64::decode(&lines.remove(1).unwrap()).unwrap()).unwrap().as_bytes(), 16u32).unwrap(),
89    &BigUint::from_radix_be(from_utf8(&base64::decode(&lines.remove(1).unwrap()).unwrap()).unwrap().as_bytes(), 16u32).unwrap()).unwrap();
90    Ok(pk)
91}
92
93
94/// Gets ecret Key params from the Pk file.
95/// Returns a ecret Key Struct or an Error.
96pub fn get_sk_params(sk_file: &File) -> Result<SecretKey, &'static str> {
97    let mut lines = vec!();
98    for line in BufReader::new(sk_file).lines() {
99        lines.push(line)
100    }
101    let sk = SecretKey::new(
102    &BigUint::from_radix_be(from_utf8(&base64::decode(&lines.remove(1).unwrap()).unwrap()).unwrap().as_bytes(), 16u32).unwrap(),
103    &BigUint::from_radix_be(from_utf8(&base64::decode(&lines.remove(1).unwrap()).unwrap()).unwrap().as_bytes(), 16u32).unwrap()).unwrap();
104    println!("{}", sk);
105    Ok(sk)
106}