rsa-pem/src/public.rs

70 lines
1.9 KiB
Rust
Raw Permalink Normal View History

2019-10-01 02:42:37 +00:00
use super::*;
2020-07-25 14:15:18 +00:00
use rsa::{PublicKeyParts, RSAPublicKey};
use std::convert::TryInto;
2019-10-01 02:42:37 +00:00
impl KeyExt for RSAPublicKey {
fn to_pem_pkcs8(&self) -> Result<String, KeyError> {
let bytes = write_pkcs1(self);
let oid = yasna::models::ObjectIdentifier::from_slice(&RSA_OID);
let contents = yasna::construct_der(|writer| {
writer.write_sequence(|writer| {
writer.next().write_sequence(|writer| {
writer.next().write_oid(&oid);
2020-03-17 01:26:54 +00:00
writer.next().write_null();
2019-10-01 02:42:37 +00:00
});
2020-03-17 01:26:54 +00:00
writer
.next()
.write_bitvec(&bit_vec::BitVec::from_bytes(&bytes));
2019-10-01 02:42:37 +00:00
});
});
let p = pem::Pem {
tag: "PUBLIC KEY".to_owned(),
contents,
};
Ok(pem::encode(&p))
}
fn from_pem_pkcs8(pem: &str) -> Result<Self, KeyError> {
let data = pem::parse(pem).map_err(|_| KeyError::Pem)?;
if data.tag != "PUBLIC KEY" {
2020-04-25 22:15:54 +00:00
return Err(KeyError::Kind);
2019-10-01 02:42:37 +00:00
}
2020-07-25 14:15:18 +00:00
data.try_into().map_err(KeyError::Parse)
2019-10-01 02:42:37 +00:00
}
fn to_pem_pkcs1(&self) -> Result<String, KeyError> {
let contents = write_pkcs1(self);
let p = pem::Pem {
tag: "RSA PUBLIC KEY".to_owned(),
contents,
};
Ok(pem::encode(&p))
}
fn from_pem_pkcs1(pem: &str) -> Result<Self, KeyError> {
let data = pem::parse(pem).map_err(|_| KeyError::Pem)?;
if data.tag != "RSA PUBLIC KEY" {
2020-04-25 22:15:54 +00:00
return Err(KeyError::Kind);
2019-10-01 02:42:37 +00:00
}
2020-07-25 14:15:18 +00:00
data.try_into().map_err(KeyError::Parse)
2019-10-01 02:42:37 +00:00
}
}
fn write_pkcs1(rsa: &RSAPublicKey) -> Vec<u8> {
yasna::construct_der(|writer| {
writer.write_sequence(|writer| {
writer.next().write_biguint(&from_dig(rsa.n()));
writer.next().write_biguint(&from_dig(rsa.e()));
})
})
}