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
Changes from 2 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
40 changes: 40 additions & 0 deletions src/crypto/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,46 @@ 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::rsa_from_public_key_bytes(
pub_key_sequence.to_captured(bcder::Mode::Der).into_bytes()
))
}

/// Creates an RSA Public Key based on the given RSAPublicKey bytes.
pub fn rsa_from_public_key_bytes(
partim marked this conversation as resolved.
Show resolved Hide resolved
bytes: Bytes
) -> Self {
let algorithm = PublicKeyFormat::Rsa;
let bits = BitString::new(0, bytes);

PublicKey { algorithm, bits }
}

/// Returns the algorithm of this public key.
pub fn algorithm(&self) -> PublicKeyFormat {
self.algorithm
Expand Down