rsa-pem/src/lib.rs
2020-03-15 21:36:06 -05:00

112 lines
2.7 KiB
Rust

use num_bigint_dig::{BigInt, BigUint, Sign};
use thiserror::Error;
mod private;
mod public;
const RSA_OID: [u64; 7] = [1, 2, 840, 113549, 1, 1, 1];
pub trait KeyExt {
fn to_pem_pkcs8(&self) -> Result<String, KeyError>;
fn from_pem_pkcs8(pem: &str) -> Result<Self, KeyError>
where
Self: Sized;
fn to_pem_pkcs1(&self) -> Result<String, KeyError>;
fn from_pem_pkcs1(pem: &str) -> Result<Self, KeyError>
where
Self: Sized;
}
#[derive(Clone, Debug, Error)]
pub enum KeyError {
#[error("Invalid key kind supplied")]
Kind,
#[error("Key not PEM-formatted")]
Pem,
#[error("Error parsing key, {}", .0)]
Parse(#[from] yasna::ASN1Error),
#[error("Constructed key is invalid")]
Validate,
#[error("Could not serialize key")]
Serialize,
}
fn to_dig(biguint: &num_bigint::BigUint) -> num_bigint_dig::BigUint {
BigUint::from_bytes_be(&biguint.to_bytes_be())
}
fn from_dig(biguint: &BigUint) -> num_bigint::BigUint {
num_bigint::BigUint::from_bytes_be(&biguint.to_bytes_be())
}
fn int_from_dig(bigint: &BigInt) -> num_bigint::BigInt {
let (sign, bytes) = bigint.to_bytes_be();
num_bigint::BigInt::from_bytes_be(sign_from_dig(sign), &bytes)
}
fn sign_from_dig(sign: Sign) -> num_bigint::Sign {
match sign {
Sign::Minus => num_bigint::Sign::Minus,
Sign::NoSign => num_bigint::Sign::NoSign,
Sign::Plus => num_bigint::Sign::Plus,
}
}
#[cfg(test)]
mod tests {
use crate::KeyExt;
use rsa::{RSAPrivateKey, RSAPublicKey};
#[test]
fn priv_can_complete_cycle_pkcs1() {
let mut rng = rand::thread_rng();
let rsa = RSAPrivateKey::new(&mut rng, 2048).unwrap();
let string = rsa.to_pem_pkcs1().unwrap();
let res = RSAPrivateKey::from_pem_pkcs1(&string);
res.unwrap();
}
#[test]
fn pub_can_complete_cycle_pkcs1() {
let mut rng = rand::thread_rng();
let rsa = RSAPrivateKey::new(&mut rng, 2048).unwrap().to_public_key();
let string = rsa.to_pem_pkcs1().unwrap();
let res = RSAPublicKey::from_pem_pkcs1(&string);
res.unwrap();
}
#[test]
fn priv_can_complete_cycle_pkcs8() {
let mut rng = rand::thread_rng();
let rsa = RSAPrivateKey::new(&mut rng, 2048).unwrap();
let string = rsa.to_pem_pkcs8().unwrap();
let res = RSAPrivateKey::from_pem_pkcs8(&string);
res.unwrap();
}
#[test]
fn pub_can_complete_cycle_pkcs8() {
let mut rng = rand::thread_rng();
let rsa = RSAPrivateKey::new(&mut rng, 2048).unwrap().to_public_key();
let string = rsa.to_pem_pkcs8().unwrap();
let res = RSAPublicKey::from_pem_pkcs8(&string);
res.unwrap();
}
}