From 7d7ced3e7c1049061a6c4dee919b44646eaf0f93 Mon Sep 17 00:00:00 2001 From: Arthur Gautier Date: Fri, 1 Dec 2023 14:13:15 -0800 Subject: [PATCH] adds rsa helpers to read public keys --- src/asymmetric/algorithm.rs | 8 ++++++++ src/asymmetric/public_key.rs | 16 ++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/asymmetric/algorithm.rs b/src/asymmetric/algorithm.rs index 6e4407e4..130d42e3 100644 --- a/src/asymmetric/algorithm.rs +++ b/src/asymmetric/algorithm.rs @@ -89,6 +89,14 @@ impl Algorithm { Algorithm::EcBp512 => 64, } } + + /// Returns true if the algorithm is RSA + pub fn is_rsa(self) -> bool { + matches!( + self, + Algorithm::Rsa2048 | Algorithm::Rsa3072 | Algorithm::Rsa4096 + ) + } } impl_algorithm_serializers!(Algorithm); diff --git a/src/asymmetric/public_key.rs b/src/asymmetric/public_key.rs index 227a6634..09ab0175 100644 --- a/src/asymmetric/public_key.rs +++ b/src/asymmetric/public_key.rs @@ -5,6 +5,8 @@ use ::ecdsa::elliptic_curve::{ bigint::Integer, generic_array::GenericArray, point::PointCompression, sec1, FieldBytesSize, PrimeCurve, }; +use num_traits::FromPrimitive; +use rsa::{BigUint, RsaPublicKey}; use serde::{Deserialize, Serialize}; /// Response from `command::get_public_key` @@ -74,6 +76,20 @@ impl PublicKey { None } } + + /// Return the RSA public key + pub fn rsa(&self) -> Option { + if !self.algorithm.is_rsa() { + return None; + } + + const EXP: u64 = 65537; + + let modulus = BigUint::from_bytes_be(&self.bytes); + let exp = BigUint::from_u64(EXP).expect("invalid static exponent"); + + RsaPublicKey::new(modulus, exp).ok() + } } impl AsRef<[u8]> for PublicKey {