From e767bdd0b1bb204cfb3453b46f9349c357c618b0 Mon Sep 17 00:00:00 2001 From: Thomas Rittson Date: Thu, 26 Oct 2023 12:21:48 +1000 Subject: [PATCH] Move pub priv key functions to rsa module --- crates/bitwarden/src/crypto/mod.rs | 4 ++++ crates/bitwarden/src/crypto/rsa.rs | 12 +++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/bitwarden/src/crypto/mod.rs b/crates/bitwarden/src/crypto/mod.rs index d27a1b33e..a281d4cc4 100644 --- a/crates/bitwarden/src/crypto/mod.rs +++ b/crates/bitwarden/src/crypto/mod.rs @@ -52,6 +52,10 @@ pub use self::rsa::RsaKeyPair; #[cfg(feature = "internal")] pub use self::rsa::encrypt_rsa; #[cfg(feature = "internal")] +pub use self::rsa::public_key_from_b64; +#[cfg(feature = "internal")] +pub use self::rsa::private_key_from_bytes; +#[cfg(feature = "internal")] #[cfg(feature = "internal")] mod fingerprint; diff --git a/crates/bitwarden/src/crypto/rsa.rs b/crates/bitwarden/src/crypto/rsa.rs index 83f076450..6c1ed8fba 100644 --- a/crates/bitwarden/src/crypto/rsa.rs +++ b/crates/bitwarden/src/crypto/rsa.rs @@ -1,6 +1,6 @@ use base64::Engine; use rsa::{ - pkcs8::{EncodePrivateKey, EncodePublicKey}, + pkcs8::{der::Decode, EncodePrivateKey, EncodePublicKey, SubjectPublicKeyInfo, DecodePrivateKey}, RsaPrivateKey, RsaPublicKey, Oaep }; @@ -54,6 +54,16 @@ pub fn encrypt_rsa(data: Vec, key: &RsaPublicKey) -> Result> { .map_err(|_| CryptoError::InvalidKey.into()) // need better error } +pub fn public_key_from_b64(b64: &str) -> Result { + let public_key_bytes = BASE64_ENGINE.decode(b64)?; + let public_key_info = SubjectPublicKeyInfo::from_der(&public_key_bytes).unwrap(); // TODO: error handling + RsaPublicKey::try_from(public_key_info).map_err(|_| Error::Crypto(CryptoError::InvalidKey)) +} + +pub fn private_key_from_bytes(bytes: &Vec) -> Result { + rsa::RsaPrivateKey::from_pkcs8_der(bytes).map_err(|_| Error::Crypto(CryptoError::InvalidKey)) +} + #[cfg(test)] mod tests { use base64::Engine;