Skip to main content

bitwarden_crypto/enc_string/
asymmetric.rs

1use std::{borrow::Cow, fmt::Display, str::FromStr};
2
3use bitwarden_encoding::{B64, FromStrVisitor};
4pub use internal::UnsignedSharedKey;
5use rsa::Oaep;
6use serde::Deserialize;
7
8use super::{from_b64_vec, split_enc_string};
9use crate::{
10    BitwardenLegacyKeyBytes, KeySlotIds, KeyStoreContext, PrivateKey, PublicKey, RawPrivateKey,
11    RawPublicKey, SymmetricCryptoKey,
12    error::{CryptoError, EncStringParseError, Result},
13    rsa::encrypt_rsa2048_oaep_sha1,
14    slow_crypto_span::{SlowCryptoOp, measure},
15};
16// This module is a workaround to avoid deprecated warnings that come from the ZeroizeOnDrop
17// macro expansion
18#[allow(deprecated)]
19mod internal {
20    #[cfg(feature = "wasm")]
21    #[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
22    const TS_CUSTOM_TYPES: &'static str = r#"
23    export type UnsignedSharedKey = Tagged<string, "UnsignedSharedKey">;
24    "#;
25
26    /// # Encrypted string primitive
27    ///
28    /// WARNING: This should not be used for new cryptographic constructions, since it does not
29    /// provide sender authentication, or cryptographic namespacing.
30    ///
31    /// [UnsignedSharedKey] is a Bitwarden specific primitive that represents an
32    /// asymmetrically encrypted symmetric key. Since the symmetric key is directly encrypted
33    /// with the public key, without any further signature, the receiver cannot guarantee the
34    /// senders identity.
35    ///
36    /// [UnsignedSharedKey] type allows for different encryption algorithms
37    /// to be used which is represented by the different variants of the enum.
38    ///
39    /// ## Note
40    ///
41    /// For backwards compatibility we will rarely if ever be able to remove support for decrypting
42    /// old variants, but we should be opinionated in which variants are used for encrypting.
43    ///
44    /// ## Variants
45    /// - [Rsa2048_OaepSha256_B64](UnsignedSharedKey::Rsa2048_OaepSha256_B64)
46    /// - [Rsa2048_OaepSha1_B64](UnsignedSharedKey::Rsa2048_OaepSha1_B64)
47    ///
48    /// ## Serialization
49    ///
50    /// [UnsignedSharedKey] implements [std::fmt::Display] and [std::str::FromStr] to allow
51    /// for easy serialization and uses a custom scheme to represent the different variants.
52    ///
53    /// The scheme is one of the following schemes:
54    /// - `[type].[data]`
55    ///
56    /// Where:
57    /// - `[type]`: is a digit number representing the variant.
58    /// - `[data]`: is the encrypted data.
59    #[allow(missing_docs)]
60    #[derive(Clone, zeroize::ZeroizeOnDrop, PartialEq)]
61    #[allow(unused, non_camel_case_types)]
62    pub enum UnsignedSharedKey {
63        /// 3
64        Rsa2048_OaepSha256_B64 { data: Vec<u8> },
65        /// 4
66        Rsa2048_OaepSha1_B64 { data: Vec<u8> },
67        /// 5
68        #[deprecated]
69        Rsa2048_OaepSha256_HmacSha256_B64 { data: Vec<u8>, mac: Vec<u8> },
70        /// 6
71        #[deprecated]
72        Rsa2048_OaepSha1_HmacSha256_B64 { data: Vec<u8>, mac: Vec<u8> },
73    }
74}
75
76/// To avoid printing sensitive information, [UnsignedSharedKey] debug prints to
77/// `UnsignedSharedKey`.
78impl std::fmt::Debug for UnsignedSharedKey {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        f.debug_struct("UnsignedSharedKey").finish()
81    }
82}
83
84/// Deserializes an [UnsignedSharedKey] from a string.
85impl FromStr for UnsignedSharedKey {
86    type Err = CryptoError;
87
88    fn from_str(s: &str) -> Result<Self, Self::Err> {
89        let (enc_type, parts) = split_enc_string(s);
90        match (enc_type, parts.len()) {
91            ("3", 1) => {
92                let data = from_b64_vec(parts[0])?;
93                Ok(UnsignedSharedKey::Rsa2048_OaepSha256_B64 { data })
94            }
95            ("4", 1) => {
96                let data = from_b64_vec(parts[0])?;
97                Ok(UnsignedSharedKey::Rsa2048_OaepSha1_B64 { data })
98            }
99            #[allow(deprecated)]
100            ("5", 2) => {
101                let data = from_b64_vec(parts[0])?;
102                let mac: Vec<u8> = from_b64_vec(parts[1])?;
103                Ok(UnsignedSharedKey::Rsa2048_OaepSha256_HmacSha256_B64 { data, mac })
104            }
105            #[allow(deprecated)]
106            ("6", 2) => {
107                let data = from_b64_vec(parts[0])?;
108                let mac: Vec<u8> = from_b64_vec(parts[1])?;
109                Ok(UnsignedSharedKey::Rsa2048_OaepSha1_HmacSha256_B64 { data, mac })
110            }
111
112            (enc_type, parts) => Err(EncStringParseError::InvalidTypeAsymm {
113                enc_type: enc_type.to_string(),
114                parts,
115            }
116            .into()),
117        }
118    }
119}
120
121impl Display for UnsignedSharedKey {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        let parts: Vec<&[u8]> = match self {
124            UnsignedSharedKey::Rsa2048_OaepSha256_B64 { data } => vec![data],
125            UnsignedSharedKey::Rsa2048_OaepSha1_B64 { data } => vec![data],
126            #[allow(deprecated)]
127            UnsignedSharedKey::Rsa2048_OaepSha256_HmacSha256_B64 { data, mac } => {
128                vec![data, mac]
129            }
130            #[allow(deprecated)]
131            UnsignedSharedKey::Rsa2048_OaepSha1_HmacSha256_B64 { data, mac } => {
132                vec![data, mac]
133            }
134        };
135
136        let encoded_parts: Vec<String> = parts
137            .iter()
138            .map(|part| B64::from(*part).to_string())
139            .collect();
140
141        write!(f, "{}.{}", self.enc_type(), encoded_parts.join("|"))?;
142
143        Ok(())
144    }
145}
146
147bitwarden_ffi::impl_wire_string!(UnsignedSharedKey);
148
149#[cfg(feature = "wasm")]
150impl TryFrom<wasm_bindgen::JsValue> for UnsignedSharedKey {
151    type Error = CryptoError;
152
153    fn try_from(value: wasm_bindgen::JsValue) -> Result<Self, Self::Error> {
154        let string = value
155            .as_string()
156            .ok_or(EncStringParseError::NoType)
157            .map_err(CryptoError::from)?;
158        Self::from_str(&string)
159    }
160}
161
162impl<'de> Deserialize<'de> for UnsignedSharedKey {
163    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
164    where
165        D: serde::Deserializer<'de>,
166    {
167        deserializer.deserialize_str(FromStrVisitor::new())
168    }
169}
170
171impl serde::Serialize for UnsignedSharedKey {
172    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
173    where
174        S: serde::Serializer,
175    {
176        serializer.serialize_str(&self.to_string())
177    }
178}
179
180impl UnsignedSharedKey {
181    /// Encapsulate a symmetric key, to be shared asymmetrically. Produces a
182    /// [UnsignedSharedKey::Rsa2048_OaepSha1_B64] variant. Note, this does not sign the data
183    /// and thus does not guarantee sender authenticity.
184    #[deprecated(note = "Use encapsulate() instead")]
185    pub fn encapsulate_key_unsigned(
186        encapsulated_key: &SymmetricCryptoKey,
187        encapsulation_key: &PublicKey,
188    ) -> Result<UnsignedSharedKey> {
189        match encapsulation_key.inner() {
190            RawPublicKey::RsaOaepSha1(rsa_public_key) => {
191                Ok(UnsignedSharedKey::Rsa2048_OaepSha1_B64 {
192                    data: encrypt_rsa2048_oaep_sha1(
193                        rsa_public_key,
194                        encapsulated_key.to_encoded().as_ref(),
195                    )?,
196                })
197            }
198        }
199    }
200
201    /// Encapsulate a symmetric key, to be shared asymmetrically. Produces a
202    /// [UnsignedSharedKey::Rsa2048_OaepSha1_B64] variant. Note, this does not sign the data
203    /// and thus does not guarantee sender authenticity.
204    pub fn encapsulate<Ids: KeySlotIds>(
205        key_to_encapsulate: Ids::Symmetric,
206        encapsulation_key: &PublicKey,
207        ctx: &KeyStoreContext<Ids>,
208    ) -> Result<UnsignedSharedKey> {
209        // Internal usage to the crypto crate is allowed
210        #[expect(deprecated)]
211        let encapsulated_key = ctx.dangerous_get_symmetric_key(key_to_encapsulate)?;
212        // Will be replaced once callers have been moved over
213        #[expect(deprecated)]
214        Self::encapsulate_key_unsigned(encapsulated_key, encapsulation_key)
215    }
216
217    /// The numerical representation of the encryption type of the [UnsignedSharedKey].
218    const fn enc_type(&self) -> u8 {
219        match self {
220            UnsignedSharedKey::Rsa2048_OaepSha256_B64 { .. } => 3,
221            UnsignedSharedKey::Rsa2048_OaepSha1_B64 { .. } => 4,
222            #[allow(deprecated)]
223            UnsignedSharedKey::Rsa2048_OaepSha256_HmacSha256_B64 { .. } => 5,
224            #[allow(deprecated)]
225            UnsignedSharedKey::Rsa2048_OaepSha1_HmacSha256_B64 { .. } => 6,
226        }
227    }
228}
229
230impl UnsignedSharedKey {
231    /// Decapsulate a symmetric key using an asymmetric decapsulation key from the key store.
232    /// Returns the key ID of the decapsulated symmetric key added to the context.
233    pub fn decapsulate<Ids: KeySlotIds>(
234        &self,
235        decapsulation_key: Ids::Private,
236        ctx: &mut KeyStoreContext<Ids>,
237    ) -> Result<Ids::Symmetric> {
238        // Internal usage to the crypto crate is allowed
239        #[expect(deprecated)]
240        let private_key = ctx.dangerous_get_private_key(decapsulation_key)?;
241        #[expect(deprecated)]
242        let key = Self::decapsulate_key_unsigned(self, private_key)
243            .map_err(|_| CryptoError::KeyDecrypt)?;
244        Ok(ctx.add_local_symmetric_key(key))
245    }
246
247    /// Decapsulate a symmetric key, shared asymmetrically.
248    /// Note: The shared key does not have a sender signature and sender authenticity is not
249    /// guaranteed.
250    #[deprecated(note = "Use decapsulate() instead")]
251    pub fn decapsulate_key_unsigned(
252        &self,
253        decapsulation_key: &PrivateKey,
254    ) -> Result<SymmetricCryptoKey> {
255        match decapsulation_key.inner() {
256            RawPrivateKey::RsaOaepSha1(rsa_private_key) => {
257                use UnsignedSharedKey::*;
258                let key_data = measure(SlowCryptoOp::RsaDecrypt, || match self {
259                    Rsa2048_OaepSha256_B64 { data } => {
260                        rsa_private_key.decrypt(Oaep::<sha2::Sha256>::new(), data)
261                    }
262                    Rsa2048_OaepSha1_B64 { data } => {
263                        rsa_private_key.decrypt(Oaep::<sha1::Sha1>::new(), data)
264                    }
265                    #[allow(deprecated)]
266                    Rsa2048_OaepSha256_HmacSha256_B64 { data, .. } => {
267                        rsa_private_key.decrypt(Oaep::<sha2::Sha256>::new(), data)
268                    }
269                    #[allow(deprecated)]
270                    Rsa2048_OaepSha1_HmacSha256_B64 { data, .. } => {
271                        rsa_private_key.decrypt(Oaep::<sha1::Sha1>::new(), data)
272                    }
273                })
274                .map_err(|_| CryptoError::KeyDecrypt)?;
275                SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(key_data))
276            }
277        }
278    }
279}
280
281/// Usually we wouldn't want to expose UnsignedSharedKeys in the API or the schemas.
282/// But during the transition phase we will expose endpoints using the UnsignedSharedKey
283/// type.
284impl schemars::JsonSchema for UnsignedSharedKey {
285    fn schema_name() -> Cow<'static, str> {
286        "UnsignedSharedKey".into()
287    }
288
289    fn json_schema(generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
290        generator.subschema_for::<String>()
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use schemars::schema_for;
297
298    use super::UnsignedSharedKey;
299    use crate::{PrivateKey, SymmetricCryptoKey};
300
301    const RSA_PRIVATE_KEY: &str = "-----BEGIN PRIVATE KEY-----
302MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCXRVrCX+2hfOQS
3038HzYUS2oc/jGVTZpv+/Ryuoh9d8ihYX9dd0cYh2tl6KWdFc88lPUH11Oxqy20Rk2
304e5r/RF6T9yM0Me3NPnaKt+hlhLtfoc0h86LnhD56A9FDUfuI0dVnPcrwNv0YJIo9
3054LwxtbqBULNvXl6wJ7WAbODrCQy5ZgMVg+iH+gGpwiqsZqHt+KuoHWcN53MSPDfa
306F4/YMB99U3TziJMOOJask1TEEnakMPln11PczNDazT17DXIxYrbPfutPdh6sLs6A
307QOajdZijfEvepgnOe7cQ7aeatiOJFrjTApKPGxOVRzEMX4XS4xbyhH0QxQeB6l16
308l8C0uxIBAgMBAAECggEASaWfeVDA3cVzOPFSpvJm20OTE+R6uGOU+7vh36TX/POq
30992qBuwbd0h0oMD32FxsXywd2IxtBDUSiFM9699qufTVuM0Q3tZw6lHDTOVG08+tP
310dr8qSbMtw7PGFxN79fHLBxejjO4IrM9lapjWpxEF+11x7r+wM+0xRZQ8sNFYG46a
311PfIaty4BGbL0I2DQ2y8I57iBCAy69eht59NLMm27fRWGJIWCuBIjlpfzET1j2HLX
312UIh5bTBNzqaN039WH49HczGE3mQKVEJZc/efk3HaVd0a1Sjzyn0QY+N1jtZN3jTR
313buDWA1AknkX1LX/0tUhuS3/7C3ejHxjw4Dk1ZLo5/QKBgQDIWvqFn0+IKRSu6Ua2
314hDsufIHHUNLelbfLUMmFthxabcUn4zlvIscJO00Tq/ezopSRRvbGiqnxjv/mYxuc
315vOUBeZtlus0Q9RTACBtw9TGoNTmQbEunJ2FOSlqbQxkBBAjgGEppRPt30iGj/VjA
316hCATq2MYOa/X4dVR51BqQAFIEwKBgQDBSIfTFKC/hDk6FKZlgwvupWYJyU9Rkyfs
317tPErZFmzoKhPkQ3YORo2oeAYmVUbS9I2iIYpYpYQJHX8jMuCbCz4ONxTCuSIXYQY
318UcUq4PglCKp31xBAE6TN8SvhfME9/MvuDssnQinAHuF0GDAhF646T3LLS1not6Vs
319zv7brwSoGwKBgQC88v/8cGfi80ssQZeMnVvq1UTXIeQcQnoY5lGHJl3K8mbS3TnX
320E6c9j417Fdz+rj8KWzBzwWXQB5pSPflWcdZO886Xu/mVGmy9RWgLuVFhXwCwsVEP
321jNX5ramRb0/vY0yzenUCninBsIxFSbIfrPtLUYCc4hpxr+sr2Mg/y6jpvQKBgBez
322MRRs3xkcuXepuI2R+BCXL1/b02IJTUf1F+1eLLGd7YV0H+J3fgNc7gGWK51hOrF9
323JBZHBGeOUPlaukmPwiPdtQZpu4QNE3l37VlIpKTF30E6mb+BqR+nht3rUjarnMXg
324AoEZ18y6/KIjpSMpqC92Nnk/EBM9EYe6Cf4eA9ApAoGAeqEUg46UTlJySkBKURGp
325Is3v1kkf5I0X8DnOhwb+HPxNaiEdmO7ckm8+tPVgppLcG0+tMdLjigFQiDUQk2y3
326WjyxP5ZvXu7U96jaJRI8PFMoE06WeVYcdIzrID2HvqH+w0UQJFrLJ/0Mn4stFAEz
327XKZBokBGnjFnTnKcs7nv/O8=
328-----END PRIVATE KEY-----";
329
330    #[test]
331    fn test_enc_string_rsa2048_oaep_sha256_b64() {
332        let key_pair = PrivateKey::from_pem(RSA_PRIVATE_KEY).unwrap();
333        let enc_str: &str = "3.SUx5gWrgmAKs/S1BoQrqOmx2Hl5fPVBVHokW17Flvm4TpBnJJRkfoitp7Jc4dfazPYjWGlckJz6X+qe+/AWilS1mxtzS0PmDy7tS5xP0GRlB39dstCd5jDw1wPmTbXiLcQ5VTvzpRAfRMEYVveTsEvVTByvEYAGSn4TnCsUDykyhRbD0YcJ4r1KHLs1b3BCBy2M1Gl5nmwckH08CAXaf8VfuBFStAGRKueovqp4euneQla+4G4fXdVvb8qKPnu0iVuALIE6nUNmeOiA3xN3d+akMxbbGxrQ1Ca4TYWjHVdj9C6abngQHkjKNYQwGUXrYo160hP4LIHn/huK6bZe5dQ==";
334        let enc_string: UnsignedSharedKey = enc_str.parse().unwrap();
335
336        let test_key = SymmetricCryptoKey::generate_seeded_for_unit_tests("test");
337        assert_eq!(enc_string.enc_type(), 3);
338
339        #[expect(deprecated)]
340        let res = enc_string.decapsulate_key_unsigned(&key_pair).unwrap();
341        assert_eq!(res, test_key);
342    }
343
344    #[test]
345    fn test_enc_string_rsa2048_oaep_sha1_b64() {
346        let private_key = PrivateKey::from_pem(RSA_PRIVATE_KEY).unwrap();
347        let enc_str: &str = "4.DMD1D5r6BsDDd7C/FE1eZbMCKrmryvAsCKj6+bO54gJNUxisOI7SDcpPLRXf+JdhqY15pT+wimQ5cD9C+6OQ6s71LFQHewXPU29l9Pa1JxGeiKqp37KLYf+1IS6UB2K3ANN35C52ZUHh2TlzIS5RuntxnpCw7APbcfpcnmIdLPJBtuj/xbFd6eBwnI3GSe5qdS6/Ixdd0dgsZcpz3gHJBKmIlSo0YN60SweDq3kTJwox9xSqdCueIDg5U4khc7RhjYx8b33HXaNJj3DwgIH8iLj+lqpDekogr630OhHG3XRpvl4QzYO45bmHb8wAh67Dj70nsZcVg6bAEFHdSFohww==";
348        let enc_string: UnsignedSharedKey = enc_str.parse().unwrap();
349
350        let test_key = SymmetricCryptoKey::generate_seeded_for_unit_tests("test");
351        assert_eq!(enc_string.enc_type(), 4);
352
353        #[expect(deprecated)]
354        let res = enc_string.decapsulate_key_unsigned(&private_key).unwrap();
355        assert_eq!(res, test_key);
356    }
357
358    #[test]
359    fn test_enc_string_rsa2048_oaep_sha1_hmac_sha256_b64() {
360        let private_key = PrivateKey::from_pem(RSA_PRIVATE_KEY).unwrap();
361        let enc_str: &str = "6.DMD1D5r6BsDDd7C/FE1eZbMCKrmryvAsCKj6+bO54gJNUxisOI7SDcpPLRXf+JdhqY15pT+wimQ5cD9C+6OQ6s71LFQHewXPU29l9Pa1JxGeiKqp37KLYf+1IS6UB2K3ANN35C52ZUHh2TlzIS5RuntxnpCw7APbcfpcnmIdLPJBtuj/xbFd6eBwnI3GSe5qdS6/Ixdd0dgsZcpz3gHJBKmIlSo0YN60SweDq3kTJwox9xSqdCueIDg5U4khc7RhjYx8b33HXaNJj3DwgIH8iLj+lqpDekogr630OhHG3XRpvl4QzYO45bmHb8wAh67Dj70nsZcVg6bAEFHdSFohww==|AA==";
362        let enc_string: UnsignedSharedKey = enc_str.parse().unwrap();
363
364        let test_key: SymmetricCryptoKey =
365            SymmetricCryptoKey::generate_seeded_for_unit_tests("test");
366        assert_eq!(enc_string.enc_type(), 6);
367
368        #[expect(deprecated)]
369        let res = enc_string.decapsulate_key_unsigned(&private_key).unwrap();
370        assert_eq!(res.to_base64(), test_key.to_base64());
371    }
372
373    #[test]
374    fn test_enc_string_serialization() {
375        #[derive(serde::Serialize, serde::Deserialize)]
376        struct Test {
377            key: UnsignedSharedKey,
378        }
379
380        let cipher = "6.ThnNc67nNr7GELyuhGGfsXNP2zJnNqhrIsjntEQ27r2qmn8vwdHbTbfO0cwt6YgSibDN0PjiCZ1O3Wb/IFq+vwvyRwFqF9145wBF8CQCbkhV+M0XvO99kh0daovtt120Nve/5ETI5PbPag9VdalKRQWZypJaqQHm5TAQVf4F5wtLlCLMBkzqTk+wkFe7BPMTGn07T+O3eJbTxXvyMZewQ7icJF0MZVA7VyWX9qElmZ89FCKowbf1BMr5pbcQ+0KdXcSVW3to43VkTp7k7COwsuH3M/i1AuVP5YN8ixjyRpvaeGqX/ap2nCHK2Wj5VxgCGT7XEls6ZknnAp9nB9qVjQ==|s3ntw5H/KKD/qsS0lUghTHl5Sm9j6m7YEdNHf0OeAFQ=";
381        let serialized = format!("{{\"key\":\"{cipher}\"}}");
382
383        let t = serde_json::from_str::<Test>(&serialized).unwrap();
384        assert_eq!(t.key.enc_type(), 6);
385        assert_eq!(t.key.to_string(), cipher);
386        assert_eq!(serde_json::to_string(&t).unwrap(), serialized);
387    }
388
389    #[test]
390    fn test_from_str_invalid() {
391        let enc_str = "7.ABC";
392        let enc_string: Result<UnsignedSharedKey, _> = enc_str.parse();
393
394        let err = enc_string.unwrap_err();
395        assert_eq!(
396            err.to_string(),
397            "EncString error, Invalid asymmetric type, got type 7 with 1 parts"
398        );
399    }
400
401    #[test]
402    fn test_debug_format() {
403        let enc_str: &str = "4.ZheRb3PCfAunyFdQYPfyrFqpuvmln9H9w5nDjt88i5A7ug1XE0LJdQHCIYJl0YOZ1gCOGkhFu/CRY2StiLmT3iRKrrVBbC1+qRMjNNyDvRcFi91LWsmRXhONVSPjywzrJJXglsztDqGkLO93dKXNhuKpcmtBLsvgkphk/aFvxbaOvJ/FHdK/iV0dMGNhc/9tbys8laTdwBlI5xIChpRcrfH+XpSFM88+Bu03uK67N9G6eU1UmET+pISJwJvMuIDMqH+qkT7OOzgL3t6I0H2LDj+CnsumnQmDsvQzDiNfTR0IgjpoE9YH2LvPXVP2wVUkiTwXD9cG/E7XeoiduHyHjw==";
404        let enc_string: UnsignedSharedKey = enc_str.parse().unwrap();
405
406        let debug_string = format!("{enc_string:?}");
407        assert_eq!(debug_string, "UnsignedSharedKey");
408    }
409
410    #[test]
411    fn test_json_schema() {
412        let schema = schema_for!(UnsignedSharedKey);
413
414        assert_eq!(
415            serde_json::to_string(&schema).unwrap(),
416            r#"{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"UnsignedSharedKey","type":"string"}"#
417        );
418    }
419}