bitwarden_crypto_primitives/rustcrypto/
rsa.rs1use rsa::{
2 BoxedUint, Oaep, RsaPrivateKey, RsaPublicKey,
3 pkcs1::DecodeRsaPrivateKey,
4 pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey},
5 traits::{PrivateKeyParts, PublicKeyParts},
6};
7use zeroize::Zeroizing;
8
9use crate::{
10 Error,
11 random::SystemRng,
12 rsa::{KeySize, OaepHash, PrivateComponents},
13};
14
15const TWO_PRIMES: usize = 2;
17
18#[derive(Clone)]
19pub(crate) struct PrivateKey(RsaPrivateKey);
20
21impl zeroize::ZeroizeOnDrop for PrivateKey {}
23const _: fn() = || {
24 fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
25 assert_zeroize_on_drop::<RsaPrivateKey>();
26};
27
28impl PrivateKey {
29 pub(crate) fn generate(size: KeySize) -> Self {
30 let bits = match size {
31 KeySize::Rsa2048 => 2048,
32 };
33 Self(RsaPrivateKey::new(&mut SystemRng, bits).expect("RSA key generation does not fail"))
34 }
35
36 pub(crate) fn from_pkcs8_der(der: &[u8]) -> Result<Self, Error> {
37 RsaPrivateKey::from_pkcs8_der(der)
38 .map(Self)
39 .map_err(|_| Error::InvalidKey)
40 }
41
42 pub(crate) fn from_pkcs8_pem(pem: &str) -> Result<Self, Error> {
43 RsaPrivateKey::from_pkcs8_pem(pem)
44 .map(Self)
45 .map_err(|_| Error::InvalidKey)
46 }
47
48 pub(crate) fn from_pkcs1_der(der: &[u8]) -> Result<Self, Error> {
49 RsaPrivateKey::from_pkcs1_der(der)
50 .map(Self)
51 .map_err(|_| Error::InvalidKey)
52 }
53
54 pub(crate) fn from_components(
55 n: &[u8],
56 e: &[u8],
57 d: &[u8],
58 primes: &[&[u8]],
59 ) -> Result<Self, Error> {
60 if primes.len() != TWO_PRIMES {
63 return Err(Error::InvalidKey);
64 }
65
66 let uint = |b: &[u8]| BoxedUint::from_be_slice_vartime(b);
67 RsaPrivateKey::from_components(
68 uint(n),
69 uint(e),
70 uint(d),
71 primes.iter().map(|p| uint(p)).collect(),
72 )
73 .map(Self)
74 .map_err(|_| Error::InvalidKey)
75 }
76
77 pub(crate) fn to_pkcs8_der(&self) -> Result<Zeroizing<Vec<u8>>, Error> {
78 let doc = self.0.to_pkcs8_der().map_err(|_| Error::InvalidKey)?;
79 Ok(Zeroizing::new(doc.as_bytes().to_vec()))
80 }
81
82 pub(crate) fn components(&self) -> PrivateComponents {
83 let primes = self.0.primes();
84 let crt = self
85 .0
86 .crt_coefficient()
87 .expect("validated keys carry a CRT coefficient");
88 PrivateComponents {
89 n: be(self.0.n()),
90 e: be(self.0.e()),
91 d: be_secret(self.0.d()),
92 p: be_secret(&primes[0]),
93 q: be_secret(&primes[1]),
94 iqmp: be_secret(&crt),
95 }
96 }
97
98 pub(crate) fn public_key(&self) -> PublicKey {
99 PublicKey(self.0.to_public_key())
100 }
101
102 pub(crate) fn decrypt_oaep(
103 &self,
104 hash: OaepHash,
105 ciphertext: &[u8],
106 ) -> Result<Zeroizing<Vec<u8>>, Error> {
107 let result = match hash {
108 OaepHash::Sha1 => self.0.decrypt(Oaep::<sha1::Sha1>::new(), ciphertext),
109 OaepHash::Sha256 => self.0.decrypt(Oaep::<sha2::Sha256>::new(), ciphertext),
110 };
111 result
112 .map(Zeroizing::new)
113 .map_err(|_| Error::DecryptionFailed)
114 }
115}
116
117#[derive(Clone, PartialEq, Eq)]
118pub(crate) struct PublicKey(RsaPublicKey);
119
120impl PublicKey {
121 pub(crate) fn from_spki_der(der: &[u8]) -> Result<Self, Error> {
122 RsaPublicKey::from_public_key_der(der)
123 .map(Self)
124 .map_err(|_| Error::InvalidKey)
125 }
126
127 pub(crate) fn to_spki_der(&self) -> Result<Vec<u8>, Error> {
128 let doc = self.0.to_public_key_der().map_err(|_| Error::InvalidKey)?;
129 Ok(doc.as_bytes().to_vec())
130 }
131
132 pub(crate) fn modulus(&self) -> Vec<u8> {
133 be(self.0.n())
134 }
135
136 pub(crate) fn exponent(&self) -> Vec<u8> {
137 be(self.0.e())
138 }
139
140 pub(crate) fn modulus_len(&self) -> usize {
141 self.0.size()
142 }
143
144 pub(crate) fn encrypt_oaep(&self, hash: OaepHash, plaintext: &[u8]) -> Result<Vec<u8>, Error> {
145 let result = match hash {
146 OaepHash::Sha1 => self
147 .0
148 .encrypt(&mut SystemRng, Oaep::<sha1::Sha1>::new(), plaintext),
149 OaepHash::Sha256 => {
150 self.0
151 .encrypt(&mut SystemRng, Oaep::<sha2::Sha256>::new(), plaintext)
152 }
153 };
154 result.map_err(|_| Error::InvalidParameters)
155 }
156}
157
158fn be(value: &BoxedUint) -> Vec<u8> {
160 let bytes = value.to_be_bytes();
161 let first = bytes
162 .iter()
163 .position(|b| *b != 0)
164 .unwrap_or(bytes.len().saturating_sub(1));
165 bytes[first..].to_vec()
166}
167
168fn be_secret(value: &BoxedUint) -> Zeroizing<Vec<u8>> {
170 let bytes = Zeroizing::new(value.to_be_bytes());
171 let first = bytes
172 .iter()
173 .position(|b| *b != 0)
174 .unwrap_or(bytes.len().saturating_sub(1));
175 Zeroizing::new(bytes[first..].to_vec())
176}