Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support creating RSA Public Keys from parts / bytes. #212

Merged
merged 5 commits into from
Jul 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 69 additions & 1 deletion src/crypto/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,62 @@ pub struct PublicKey {


impl PublicKey {
/// Creates an RSA Public Key based on the supplied exponent and modulus.
///
/// See:
/// [RFC 4055]: https://tools.ietf.org/html/rfc4055
///
/// An RSA Public Key uses the following DER encoded structure inside its
/// BitString component:
///
/// ```txt
/// RSAPublicKey ::= SEQUENCE {
/// modulus INTEGER, -- n
/// publicExponent INTEGER } -- e
/// ```
pub fn rsa_from_components(
modulus: &[u8], // n
exponent: &[u8] // e
) -> Result<Self, bcder::decode::Error> {
let modulus = bcder::Unsigned::from_slice(modulus)?;
let exponent = bcder::Unsigned::from_slice(exponent)?;

let pub_key_sequence = bcder::encode::sequence((
modulus.encode(),
exponent.encode()
));

Ok(PublicKey {
algorithm: PublicKeyFormat::Rsa,
bits: BitString::new(
0,
pub_key_sequence.to_captured(bcder::Mode::Der).into_bytes()
),
})
}

/// Creates an RSA public key from the key’s bits.
///
/// Note that this is _not_ the DER-encoded public key written by, for
/// instance, the OpenSSL command line tools. These files contain the
/// complete public key including the algorithm and need to be read
/// with [`PublicKey::decode`].
pub fn rsa_from_bits_bytes(
bytes: Bytes
) -> Result<Self, bcder::decode::Error> {
Mode::Der.decode(bytes.clone(), |cons| {
cons.take_sequence(|cons| {
let _ = bcder::Unsigned::take_from(cons)?;
let _ = bcder::Unsigned::take_from(cons)?;
Ok(())
})
})?;
Ok(PublicKey {
algorithm: PublicKeyFormat::Rsa,
bits: BitString::new(0, bytes)
})
}

/// Returns the algorithm of this public key.
pub fn algorithm(&self) -> PublicKeyFormat {
self.algorithm
Expand Down Expand Up @@ -394,4 +450,16 @@ mod test {

assert_eq!(pub_key, &de);
}
}

#[test]
fn rsa_from_public_key_bytes() {
let key = PublicKey::decode(
include_bytes!("../../test-data/rsa-key.public.der").as_ref(),
).unwrap();
assert!(
PublicKey::rsa_from_bits_bytes(
key.bits_bytes()
).is_ok()
);
}
}
Binary file added test-data/rsa-key.private.der
Binary file not shown.
Binary file added test-data/rsa-key.public.der
Binary file not shown.