Skip to main content

bitwarden_crypto/keys/
symmetric_crypto_key.rs

1use std::{pin::Pin, str::FromStr};
2
3use bitwarden_encoding::{B64, FromStrVisitor};
4use ciborium::{Value, value::Integer};
5use coset::{
6    CborSerializable, RegisteredLabelWithPrivate,
7    iana::{EnumI64, KeyOperation, KeyParameter, KeyType, SymmetricKeyParameter},
8};
9use hybrid_array::Array;
10use rand::RngExt;
11#[cfg(test)]
12use rand::SeedableRng;
13#[cfg(test)]
14use rand_chacha::ChaChaRng;
15use serde::{Deserialize, Serialize};
16#[cfg(test)]
17use sha2::Digest;
18use subtle::{Choice, ConstantTimeEq};
19use typenum::{U32, U64};
20use zeroize::{Zeroize, ZeroizeOnDrop};
21
22use super::{
23    key_encryptable::CryptoKey,
24    key_id::{KEY_ID_SIZE, KeyId},
25};
26use crate::{
27    BitwardenLegacyKeyBytes, ContentFormat, CoseKeyBytes, CoseKeyThumbprint, CryptoError, cose,
28    cose::{
29        CoseKeyThumbprintExt, symmetric::CoseContentEncryptionAlgorithm,
30        thumbprint_from_required_params,
31    },
32    error::EncodingError,
33};
34
35#[cfg(feature = "wasm")]
36#[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
37const TS_CUSTOM_TYPES: &'static str = r#"
38export type SymmetricKey = Tagged<string, "SymmetricKey">;
39"#;
40
41bitwarden_ffi::impl_wire_string!(
42    SymmetricCryptoKey,
43    parse = |wire: String| {
44        let b64 = B64::try_from(wire).map_err(|err| err.to_string())?;
45        SymmetricCryptoKey::try_from(b64).map_err(|err| err.to_string())
46    },
47    format = |key: SymmetricCryptoKey| key.to_base64().to_string(),
48);
49
50#[cfg(feature = "wasm")]
51impl TryFrom<wasm_bindgen::JsValue> for SymmetricCryptoKey {
52    type Error = CryptoError;
53
54    fn try_from(value: wasm_bindgen::JsValue) -> Result<Self, Self::Error> {
55        let string = value.as_string().ok_or(CryptoError::InvalidKey)?;
56        Self::try_from(string)
57    }
58}
59
60/// The symmetric key algorithm to use when generating a new symmetric key.
61#[derive(Clone, Copy, Debug, PartialEq)]
62pub enum SymmetricKeyAlgorithm {
63    /// Used for V1 user keys and data encryption
64    Aes256CbcHmac,
65    /// Used by old PIN PasswordProtectedKeyEnvelope
66    XChaCha20Poly1305,
67    /// FIPS-approved AEAD.
68    /// Used as content encryption key in:
69    /// [`DataEnvelope`](crate::safe::DataEnvelope)s.
70    /// [`PasswordProtectedKeyEnvelope`](crate::safe::PasswordProtectedKeyEnvelope)
71    ///
72    /// May not be used for multi-device scoped keys such as the user-key or organization-key
73    Aes256Gcm,
74    /// Extended-nonce AES-256-GCM. Used for V2 user keys and as a general-purpose
75    /// encryption/wrapping key.
76    XAes256Gcm,
77}
78
79/// [Aes256CbcKey] is a symmetric encryption key, consisting of one 256-bit key,
80/// used to decrypt legacy type 0 enc strings. The data is not authenticated
81/// so this should be used with caution, and removed where possible.
82#[derive(ZeroizeOnDrop, Clone)]
83pub struct Aes256CbcKey {
84    /// Uses a pinned heap data structure, as noted in [Pinned heap data][crate#pinned-heap-data]
85    pub(crate) enc_key: Pin<Box<Array<u8, U32>>>,
86}
87
88impl ConstantTimeEq for Aes256CbcKey {
89    fn ct_eq(&self, other: &Self) -> Choice {
90        self.enc_key.ct_eq(&other.enc_key)
91    }
92}
93
94impl PartialEq for Aes256CbcKey {
95    fn eq(&self, other: &Self) -> bool {
96        self.ct_eq(other).into()
97    }
98}
99
100/// The size of the encryption half of an [`Aes256CbcHmacKey`].
101pub(crate) const AES256_CBC_HMAC_ENC_KEY_SIZE: usize = 32;
102/// The size of the MAC half of an [`Aes256CbcHmacKey`].
103pub(crate) const AES256_CBC_HMAC_MAC_KEY_SIZE: usize = 32;
104/// The size of the composite `enc_key || mac_key` buffer of an [`Aes256CbcHmacKey`].
105pub(crate) const AES256_CBC_HMAC_KEY_SIZE: usize =
106    AES256_CBC_HMAC_ENC_KEY_SIZE + AES256_CBC_HMAC_MAC_KEY_SIZE;
107
108/// [Aes256CbcHmacKey] is a symmetric encryption key consisting
109/// of two 256-bit keys, one for encryption and one for MAC
110#[derive(ZeroizeOnDrop, Clone)]
111pub struct Aes256CbcHmacKey {
112    /// The encryption and MAC keys, stored contiguously as `enc_key || mac_key`.
113    ///
114    /// They are kept in one buffer rather than two so that the 64-byte composite form — the layout
115    /// used by the byte serialization, by the
116    /// [`Aes256CbcHmacSha256Aead`](crate::hazmat::symmetric_encryption::Aes256CbcHmacSha256Aead)
117    /// cipher, and by this key's COSE key view — can be borrowed instead of copied. Use
118    /// [`Aes256CbcHmacKey::enc_key`] and [`Aes256CbcHmacKey::mac_key`] for zero-copy views of the
119    /// individual halves.
120    ///
121    /// Uses a pinned heap data structure, as noted in [Pinned heap data][crate#pinned-heap-data]
122    pub(crate) key: Pin<Box<Array<u8, U64>>>,
123}
124
125impl ConstantTimeEq for Aes256CbcHmacKey {
126    fn ct_eq(&self, other: &Self) -> Choice {
127        self.key.ct_eq(&other.key)
128    }
129}
130
131impl Aes256CbcHmacKey {
132    /// Builds a key from its two halves.
133    pub(crate) fn new(
134        enc_key: &[u8; AES256_CBC_HMAC_ENC_KEY_SIZE],
135        mac_key: &[u8; AES256_CBC_HMAC_MAC_KEY_SIZE],
136    ) -> Self {
137        let mut key = Box::pin(Array::<u8, U64>::default());
138        let (enc, mac) = key.split_at_mut(AES256_CBC_HMAC_ENC_KEY_SIZE);
139        enc.copy_from_slice(enc_key);
140        mac.copy_from_slice(mac_key);
141        Self { key }
142    }
143
144    /// Returns the 64-byte composite key (`enc_key || mac_key`), which is the layout expected by
145    /// the [`Aes256CbcHmacSha256`](crate::hazmat::symmetric_encryption::Aes256CbcHmacSha256) and
146    /// [`Aes256CbcHmacSha256Aead`](crate::hazmat::symmetric_encryption::Aes256CbcHmacSha256Aead)
147    /// ciphers.
148    pub(crate) fn as_composite_key(&self) -> &[u8; AES256_CBC_HMAC_KEY_SIZE] {
149        &self.key.0
150    }
151
152    /// Returns the composite key as a slice. This is also this key's legacy byte serialization.
153    pub(crate) fn as_slice(&self) -> &[u8] {
154        self.key.as_slice()
155    }
156
157    /// Returns a zero-copy view of the 256-bit encryption key.
158    pub(crate) fn enc_key(&self) -> &[u8; AES256_CBC_HMAC_ENC_KEY_SIZE] {
159        let (enc_key, _) = self.key.split_at(AES256_CBC_HMAC_ENC_KEY_SIZE);
160        enc_key
161            .try_into()
162            .expect("first half of a 64-byte key is always 32 bytes")
163    }
164
165    /// Returns a zero-copy view of the 256-bit MAC key.
166    pub(crate) fn mac_key(&self) -> &[u8; AES256_CBC_HMAC_MAC_KEY_SIZE] {
167        let (_, mac_key) = self.key.split_at(AES256_CBC_HMAC_ENC_KEY_SIZE);
168        mac_key
169            .try_into()
170            .expect("second half of a 64-byte key is always 32 bytes")
171    }
172
173    /// Returns the key ID of this key.
174    ///
175    /// Unlike the other COSE key types, this key has no field to store a key ID in — it is
176    /// serialized as a bare 64-byte blob with no `kid`. The ID is therefore *derived*: it is the
177    /// key's own [RFC 9679](https://www.rfc-editor.org/rfc/rfc9679) thumbprint truncated to
178    /// [`KEY_ID_SIZE`] bytes. Two keys with identical key material consequently share an ID, and a
179    /// key's ID is stable across serialization round-trips.
180    pub(crate) fn key_id(&self) -> KeyId {
181        let thumbprint = symmetric_key_thumbprint(self.as_slice());
182        let mut key_id = [0u8; KEY_ID_SIZE];
183        key_id.copy_from_slice(&thumbprint.as_bytes()[..KEY_ID_SIZE]);
184        KeyId::from(key_id)
185    }
186}
187
188/// Computes the [RFC 9679](https://www.rfc-editor.org/rfc/rfc9679) thumbprint of a COSE `Symmetric`
189/// key with the given `k` bytes. `kty` and `k` are the only required parameters for this key type,
190/// so they are the only ones hashed.
191fn symmetric_key_thumbprint(key_bytes: &[u8]) -> CoseKeyThumbprint {
192    thumbprint_from_required_params(vec![
193        (
194            KeyParameter::Kty.to_i64(),
195            Value::Integer(Integer::from(KeyType::Symmetric.to_i64())),
196        ),
197        (
198            SymmetricKeyParameter::K.to_i64(),
199            Value::Bytes(key_bytes.to_vec()),
200        ),
201    ])
202}
203
204impl PartialEq for Aes256CbcHmacKey {
205    fn eq(&self, other: &Self) -> bool {
206        self.ct_eq(other).into()
207    }
208}
209
210/// [XChaCha20Poly1305Key] is a symmetric encryption key consisting
211/// of one 256-bit key, and contains a key id. In contrast to the
212/// [Aes256CbcKey] and [Aes256CbcHmacKey], this key type is used to create
213/// CoseEncrypt0 messages.
214#[derive(Zeroize, Clone)]
215pub struct XChaCha20Poly1305Key {
216    pub(crate) key_id: KeyId,
217    pub(crate) enc_key: Pin<Box<Array<u8, U32>>>,
218    /// Controls which key operations are allowed with this key. Note: Only checking decrypt is
219    /// implemented right now, and implementing is tracked here <https://bitwarden.atlassian.net/browse/PM-27513>.
220    /// Further, disabling decrypt will also disable unwrap. The only use-case so far is
221    /// `DataEnvelope`.
222    #[zeroize(skip)]
223    pub(crate) supported_operations: Vec<KeyOperation>,
224}
225
226impl XChaCha20Poly1305Key {
227    /// Creates a new XChaCha20Poly1305Key with a securely sampled cryptographic key and key id.
228    pub fn make() -> Self {
229        let mut rng = bitwarden_random::rng();
230        let mut enc_key = Box::pin(Array::<u8, U32>::default());
231        rng.fill(enc_key.as_mut_slice());
232        let key_id = KeyId::make();
233
234        Self {
235            enc_key,
236            key_id,
237            supported_operations: vec![
238                KeyOperation::Decrypt,
239                KeyOperation::Encrypt,
240                KeyOperation::WrapKey,
241                KeyOperation::UnwrapKey,
242            ],
243        }
244    }
245}
246
247impl ConstantTimeEq for XChaCha20Poly1305Key {
248    fn ct_eq(&self, other: &Self) -> Choice {
249        self.enc_key.ct_eq(&other.enc_key) & self.key_id.ct_eq(&other.key_id)
250    }
251}
252
253impl PartialEq for XChaCha20Poly1305Key {
254    fn eq(&self, other: &Self) -> bool {
255        self.ct_eq(other).into()
256    }
257}
258
259/// [Aes256GcmKey] is a symmetric AEAD key consisting of one 256-bit key
260#[derive(Zeroize, Clone)]
261pub struct Aes256GcmKey {
262    pub(crate) key_id: KeyId,
263    pub(crate) enc_key: Pin<Box<Array<u8, U32>>>,
264    /// Controls which key operations are allowed with this key. See
265    /// [`XChaCha20Poly1305Key::supported_operations`].
266    #[zeroize(skip)]
267    pub(crate) supported_operations: Vec<KeyOperation>,
268}
269
270impl Aes256GcmKey {
271    /// Creates a new Aes256GcmKey with a securely sampled cryptographic key and key id.
272    pub fn make() -> Self {
273        let mut rng = bitwarden_random::rng();
274        let mut enc_key = Box::pin(Array::<u8, U32>::default());
275        rng.fill(enc_key.as_mut_slice());
276        let key_id = KeyId::make();
277
278        Self {
279            enc_key,
280            key_id,
281            supported_operations: vec![
282                KeyOperation::Decrypt,
283                KeyOperation::Encrypt,
284                KeyOperation::WrapKey,
285                KeyOperation::UnwrapKey,
286            ],
287        }
288    }
289
290    pub(crate) fn disable_key_operation(&mut self, op: KeyOperation) -> &mut Self {
291        self.supported_operations.retain(|k| *k != op);
292        self
293    }
294}
295
296impl ConstantTimeEq for Aes256GcmKey {
297    fn ct_eq(&self, other: &Self) -> Choice {
298        self.enc_key.ct_eq(&other.enc_key) & self.key_id.ct_eq(&other.key_id)
299    }
300}
301
302impl PartialEq for Aes256GcmKey {
303    fn eq(&self, other: &Self) -> bool {
304        self.ct_eq(other).into()
305    }
306}
307
308/// An XAES-256-GCM key consisting of one 256-bit key and a key ID.
309#[derive(Zeroize, Clone)]
310pub struct XAes256GcmKey {
311    pub(crate) key_id: KeyId,
312    pub(crate) enc_key: Pin<Box<Array<u8, U32>>>,
313    #[zeroize(skip)]
314    pub(crate) supported_operations: Vec<KeyOperation>,
315}
316
317impl XAes256GcmKey {
318    /// Creates a new XAES-256-GCM key with securely sampled key bytes and key ID.
319    pub fn make() -> Self {
320        let mut rng = bitwarden_random::rng();
321        let mut enc_key = Box::pin(Array::<u8, U32>::default());
322        rng.fill(enc_key.as_mut_slice());
323
324        Self {
325            key_id: KeyId::make(),
326            enc_key,
327            supported_operations: vec![
328                KeyOperation::Decrypt,
329                KeyOperation::Encrypt,
330                KeyOperation::WrapKey,
331                KeyOperation::UnwrapKey,
332            ],
333        }
334    }
335}
336
337impl ConstantTimeEq for XAes256GcmKey {
338    fn ct_eq(&self, other: &Self) -> Choice {
339        self.enc_key.ct_eq(&other.enc_key) & self.key_id.ct_eq(&other.key_id)
340    }
341}
342
343impl PartialEq for XAes256GcmKey {
344    fn eq(&self, other: &Self) -> bool {
345        self.ct_eq(other).into()
346    }
347}
348
349/// A borrowed view over a symmetric key that can be used as a COSE content-encryption key.
350pub(crate) enum CoseKeyView<'a> {
351    Aes256Gcm(&'a Aes256GcmKey),
352    XChaCha20Poly1305(&'a XChaCha20Poly1305Key),
353    XAes256Gcm(&'a XAes256GcmKey),
354    Aes256CbcHmac(&'a Aes256CbcHmacKey),
355}
356
357impl CoseKeyView<'_> {
358    /// Returns the key ID of the viewed key.
359    ///
360    /// This is returned by value rather than by reference because
361    /// [`CoseKeyView::Aes256CbcHmac`] derives its ID from the key material instead of storing one;
362    /// see [`Aes256CbcHmacKey::key_id`].
363    pub(crate) fn key_id(&self) -> KeyId {
364        match self {
365            CoseKeyView::Aes256Gcm(k) => k.key_id.clone(),
366            CoseKeyView::XChaCha20Poly1305(k) => k.key_id.clone(),
367            CoseKeyView::XAes256Gcm(k) => k.key_id.clone(),
368            CoseKeyView::Aes256CbcHmac(k) => k.key_id(),
369        }
370    }
371
372    /// Returns the key material in the layout the corresponding [`algorithm`](Self::algorithm)
373    /// expects as its content-encryption key.
374    pub(crate) fn key_bytes(&self) -> &[u8] {
375        match self {
376            CoseKeyView::Aes256Gcm(k) => k.enc_key.as_slice(),
377            CoseKeyView::XChaCha20Poly1305(k) => k.enc_key.as_slice(),
378            CoseKeyView::XAes256Gcm(k) => k.enc_key.as_slice(),
379            CoseKeyView::Aes256CbcHmac(k) => k.as_slice(),
380        }
381    }
382
383    pub(crate) fn algorithm(&self) -> CoseContentEncryptionAlgorithm {
384        match self {
385            CoseKeyView::Aes256Gcm(_) => CoseContentEncryptionAlgorithm::Aes256Gcm,
386            CoseKeyView::XChaCha20Poly1305(_) => CoseContentEncryptionAlgorithm::XChaCha20Poly1305,
387            CoseKeyView::XAes256Gcm(_) => CoseContentEncryptionAlgorithm::XAes256Gcm,
388            CoseKeyView::Aes256CbcHmac(_) => {
389                CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead
390            }
391        }
392    }
393}
394
395/// A symmetric encryption key. Used to encrypt and decrypt [`EncString`](crate::EncString)
396#[derive(ZeroizeOnDrop, Clone)]
397pub enum SymmetricCryptoKey {
398    #[allow(missing_docs)]
399    Aes256CbcKey(Aes256CbcKey),
400    #[allow(missing_docs)]
401    Aes256CbcHmacKey(Aes256CbcHmacKey),
402    /// Data encrypted by XChaCha20Poly1305Key keys has type
403    /// [`Cose_Encrypt0_B64`](crate::EncString::Cose_Encrypt0_B64)
404    XChaCha20Poly1305Key(XChaCha20Poly1305Key),
405    /// FIPS-approved AES-256-GCM key, used as the content-encryption key for FIPS
406    /// [`DataEnvelope`](crate::safe::DataEnvelope)s. Encoded as a COSE key.
407    Aes256GcmKey(Aes256GcmKey),
408    /// Extended-nonce AES-256-GCM key. Encoded as a COSE key and used with
409    /// type-7 EncStrings.
410    XAes256GcmKey(XAes256GcmKey),
411}
412
413impl SymmetricCryptoKey {
414    // enc type 0 old static format
415    const AES256_CBC_KEY_LEN: usize = 32;
416    // enc type 2 old static format
417    const AES256_CBC_HMAC_KEY_LEN: usize = 64;
418
419    /// Generate a new random AES256_CBC [SymmetricCryptoKey]
420    ///
421    /// WARNING: This function should only be used with a proper cryptographic RNG. If you do not
422    /// have a good reason for using this function, use
423    /// [SymmetricCryptoKey::make_aes256_cbc_hmac_key] instead.
424    pub(crate) fn make_aes256_cbc_hmac_key_internal(mut rng: impl rand::CryptoRng) -> Self {
425        let mut key = Box::pin(Array::<u8, U64>::default());
426        // Drawn as two separate 32-byte fills, matching the order and sizes used before the two
427        // halves shared one buffer, so seeded generation stays byte-for-byte identical.
428        let (enc_key, mac_key) = key.split_at_mut(AES256_CBC_HMAC_ENC_KEY_SIZE);
429        rng.fill(enc_key);
430        rng.fill(mac_key);
431
432        Self::Aes256CbcHmacKey(Aes256CbcHmacKey { key })
433    }
434
435    /// Make a new [SymmetricCryptoKey] for the specified algorithm
436    pub fn make(algorithm: SymmetricKeyAlgorithm) -> Self {
437        match algorithm {
438            SymmetricKeyAlgorithm::Aes256CbcHmac => Self::make_aes256_cbc_hmac_key(),
439            SymmetricKeyAlgorithm::XChaCha20Poly1305 => Self::make_xchacha20_poly1305_key(),
440            SymmetricKeyAlgorithm::Aes256Gcm => Self::Aes256GcmKey(Aes256GcmKey::make()),
441            SymmetricKeyAlgorithm::XAes256Gcm => Self::XAes256GcmKey(XAes256GcmKey::make()),
442        }
443    }
444
445    /// Generate a new random AES256_CBC_HMAC [SymmetricCryptoKey]
446    pub(crate) fn make_aes256_cbc_hmac_key() -> Self {
447        let rng = bitwarden_random::rng();
448        Self::make_aes256_cbc_hmac_key_internal(rng)
449    }
450
451    /// Generate a new random XChaCha20Poly1305 [SymmetricCryptoKey]
452    pub(crate) fn make_xchacha20_poly1305_key() -> Self {
453        let mut rng = bitwarden_random::rng();
454        let mut enc_key = Box::pin(Array::<u8, U32>::default());
455        rng.fill(enc_key.as_mut_slice());
456        Self::XChaCha20Poly1305Key(XChaCha20Poly1305Key {
457            enc_key,
458            key_id: KeyId::make(),
459            supported_operations: vec![
460                KeyOperation::Decrypt,
461                KeyOperation::Encrypt,
462                KeyOperation::WrapKey,
463                KeyOperation::UnwrapKey,
464            ],
465        })
466    }
467
468    /// Encodes the key to a byte array representation, that is separated by size.
469    /// [SymmetricCryptoKey::Aes256CbcHmacKey] and [SymmetricCryptoKey::Aes256CbcKey] are
470    /// encoded as 64 and 32 bytes respectively. COSE-serialized variants are encoded as at least
471    /// 65 bytes using padding.
472    ///
473    /// This can be used for storage and transmission in the old byte array format.
474    /// When the wrapping key is a COSE key, and the wrapped key is a COSE key, then this should
475    /// not use the byte representation but instead use the COSE key representation.
476    pub fn to_encoded(&self) -> BitwardenLegacyKeyBytes {
477        let encoded_key = self.to_encoded_raw();
478        match encoded_key {
479            EncodedSymmetricKey::BitwardenLegacyKey(_) => {
480                let encoded_key: Vec<u8> = encoded_key.into();
481                BitwardenLegacyKeyBytes::from(encoded_key)
482            }
483            EncodedSymmetricKey::CoseKey(_) => {
484                let mut encoded_key: Vec<u8> = encoded_key.into();
485                pad_key(&mut encoded_key, (Self::AES256_CBC_HMAC_KEY_LEN + 1) as u8); // This is less than 255
486                BitwardenLegacyKeyBytes::from(encoded_key)
487            }
488        }
489    }
490
491    /// Generate a new random [SymmetricCryptoKey] for unit tests. Note: DO NOT USE THIS
492    /// IN PRODUCTION CODE.
493    #[cfg(test)]
494    pub fn generate_seeded_for_unit_tests(seed: &str) -> Self {
495        // Keep this separate from the other generate function to not break test vectors.
496        let mut seeded_rng = ChaChaRng::from_seed(sha2::Sha256::digest(seed.as_bytes()).into());
497        let mut key = Box::pin(Array::<u8, U64>::default());
498        // Two separate 32-byte fills, as above, so the generated key is unchanged.
499        let (enc_key, mac_key) = key.split_at_mut(AES256_CBC_HMAC_ENC_KEY_SIZE);
500        seeded_rng.fill(enc_key);
501        seeded_rng.fill(mac_key);
502
503        SymmetricCryptoKey::Aes256CbcHmacKey(Aes256CbcHmacKey { key })
504    }
505
506    /// Creates the byte representation of the key, without any padding. This should not
507    /// be used directly for creating serialized key representations, instead,
508    /// [SymmetricCryptoKey::to_encoded] should be used.
509    ///
510    /// [SymmetricCryptoKey::Aes256CbcHmacKey] and
511    /// [SymmetricCryptoKey::Aes256CbcKey] are encoded as 64 and 32 byte arrays
512    /// respectively, representing the key bytes directly. XChaCha20-Poly1305,
513    /// AES-256-GCM, and XAES-256-GCM keys are encoded as serialized COSE keys.
514    /// A COSE key can be directly encrypted with a COSE key content format or
515    /// represented as a byte array. When represented as a byte array, the array
516    /// is padded to be larger than the byte array representation of the other
517    /// aforementioned key types.
518    pub(crate) fn to_encoded_raw(&self) -> EncodedSymmetricKey {
519        match self {
520            Self::Aes256CbcKey(key) => {
521                EncodedSymmetricKey::BitwardenLegacyKey(key.enc_key.to_vec().into())
522            }
523            Self::Aes256CbcHmacKey(key) => {
524                EncodedSymmetricKey::BitwardenLegacyKey(key.as_slice().to_vec().into())
525            }
526            Self::XChaCha20Poly1305Key(key) => {
527                let builder = coset::CoseKeyBuilder::new_symmetric_key(key.enc_key.to_vec());
528                let mut cose_key = builder.key_id((&key.key_id).into());
529                for op in &key.supported_operations {
530                    cose_key = cose_key.add_key_op(*op);
531                }
532                let mut cose_key = cose_key.build();
533                cose_key.alg = Some(RegisteredLabelWithPrivate::PrivateUse(
534                    cose::XCHACHA20_POLY1305,
535                ));
536                EncodedSymmetricKey::CoseKey(
537                    cose_key
538                        .to_vec()
539                        .expect("cose key serialization should not fail")
540                        .into(),
541                )
542            }
543            Self::XAes256GcmKey(key) => {
544                let builder = coset::CoseKeyBuilder::new_symmetric_key(key.enc_key.to_vec());
545                let mut cose_key = builder.key_id((&key.key_id).into());
546                for op in &key.supported_operations {
547                    cose_key = cose_key.add_key_op(*op);
548                }
549                let mut cose_key = cose_key.build();
550                cose_key.alg = Some(RegisteredLabelWithPrivate::PrivateUse(cose::XAES_256_GCM));
551                EncodedSymmetricKey::CoseKey(
552                    cose_key
553                        .to_vec()
554                        .expect("cose key serialization should not fail")
555                        .into(),
556                )
557            }
558            Self::Aes256GcmKey(key) => {
559                let builder = coset::CoseKeyBuilder::new_symmetric_key(key.enc_key.to_vec());
560                let mut cose_key = builder.key_id((&key.key_id).into());
561                for op in &key.supported_operations {
562                    cose_key = cose_key.add_key_op(*op);
563                }
564                let mut cose_key = cose_key.build();
565                cose_key.alg = Some(RegisteredLabelWithPrivate::Assigned(
566                    coset::iana::Algorithm::A256GCM,
567                ));
568                EncodedSymmetricKey::CoseKey(
569                    cose_key
570                        .to_vec()
571                        .expect("cose key serialization should not fail")
572                        .into(),
573                )
574            }
575        }
576    }
577
578    pub(crate) fn try_from_cose(serialized_key: &[u8]) -> Result<Self, CryptoError> {
579        let cose_key =
580            coset::CoseKey::from_slice(serialized_key).map_err(|_| CryptoError::InvalidKey)?;
581        let key = SymmetricCryptoKey::try_from(&cose_key)?;
582        Ok(key)
583    }
584
585    #[allow(missing_docs)]
586    pub fn to_base64(&self) -> B64 {
587        B64::from(self.to_encoded().as_ref())
588    }
589
590    /// Returns the key ID of the key, if it has one. Every authenticated key variant has a key ID;
591    /// only the unauthenticated [`SymmetricCryptoKey::Aes256CbcKey`] does not.
592    ///
593    /// [`SymmetricCryptoKey::Aes256CbcHmacKey`] has no field to store a key ID in, and derives one
594    /// from its key material instead: its RFC 9679 thumbprint, truncated to the key ID length. Two
595    /// such keys with identical key material therefore share an ID.
596    pub fn key_id(&self) -> Option<KeyId> {
597        match self {
598            Self::Aes256CbcKey(_) => None,
599            Self::Aes256CbcHmacKey(key) => Some(key.key_id()),
600            Self::XChaCha20Poly1305Key(key) => Some(key.key_id.clone()),
601            Self::Aes256GcmKey(key) => Some(key.key_id.clone()),
602            Self::XAes256GcmKey(key) => Some(key.key_id.clone()),
603        }
604    }
605
606    /// Returns a [`CoseKeyView`] for every symmetric key variant usable as a COSE
607    /// content-encryption key. Only the unauthenticated [`SymmetricCryptoKey::Aes256CbcKey`]
608    /// returns `None`.
609    pub(crate) fn as_cose_key_view(&self) -> Option<CoseKeyView<'_>> {
610        match self {
611            Self::Aes256GcmKey(k) => Some(CoseKeyView::Aes256Gcm(k)),
612            Self::XChaCha20Poly1305Key(k) => Some(CoseKeyView::XChaCha20Poly1305(k)),
613            Self::XAes256GcmKey(k) => Some(CoseKeyView::XAes256Gcm(k)),
614            Self::Aes256CbcHmacKey(k) => Some(CoseKeyView::Aes256CbcHmac(k)),
615            Self::Aes256CbcKey(_) => None,
616        }
617    }
618}
619
620impl CoseKeyThumbprintExt for SymmetricCryptoKey {
621    /// Computes the RFC 9679 thumbprint of this symmetric key.
622    ///
623    /// Returns an error for the unauthenticated legacy AES-CBC key, which is not representable as
624    /// a COSE key.
625    fn thumbprint(&self) -> Result<CoseKeyThumbprint, CryptoError> {
626        let view = self
627            .as_cose_key_view()
628            .ok_or(EncodingError::UnsupportedValue(
629                "unauthenticated AES-CBC keys are not COSE keys and have no thumbprint",
630            ))?;
631        Ok(symmetric_key_thumbprint(view.key_bytes()))
632    }
633}
634
635impl ConstantTimeEq for SymmetricCryptoKey {
636    /// Note: This is constant time with respect to comparing two keys of the same type, but not
637    /// constant type with respect to the fact that different keys are compared. If two types of
638    /// different keys are compared, then this does have different timing.
639    fn ct_eq(&self, other: &SymmetricCryptoKey) -> Choice {
640        use SymmetricCryptoKey::*;
641        match (self, other) {
642            (Aes256CbcKey(a), Aes256CbcKey(b)) => a.ct_eq(b),
643            (Aes256CbcKey(_), _) => Choice::from(0),
644
645            (Aes256CbcHmacKey(a), Aes256CbcHmacKey(b)) => a.ct_eq(b),
646            (Aes256CbcHmacKey(_), _) => Choice::from(0),
647
648            (XChaCha20Poly1305Key(a), XChaCha20Poly1305Key(b)) => a.ct_eq(b),
649            (XChaCha20Poly1305Key(_), _) => Choice::from(0),
650
651            (Aes256GcmKey(a), Aes256GcmKey(b)) => a.ct_eq(b),
652            (Aes256GcmKey(_), _) => Choice::from(0),
653
654            (XAes256GcmKey(a), XAes256GcmKey(b)) => a.ct_eq(b),
655            (XAes256GcmKey(_), _) => Choice::from(0),
656        }
657    }
658}
659
660impl PartialEq for SymmetricCryptoKey {
661    fn eq(&self, other: &Self) -> bool {
662        self.ct_eq(other).into()
663    }
664}
665
666impl TryFrom<String> for SymmetricCryptoKey {
667    type Error = CryptoError;
668
669    fn try_from(value: String) -> Result<Self, Self::Error> {
670        let bytes = B64::try_from(value).map_err(|_| CryptoError::InvalidKey)?;
671        Self::try_from(bytes)
672    }
673}
674
675impl TryFrom<B64> for SymmetricCryptoKey {
676    type Error = CryptoError;
677
678    fn try_from(value: B64) -> Result<Self, Self::Error> {
679        Self::try_from(&BitwardenLegacyKeyBytes::from(&value))
680    }
681}
682
683impl TryFrom<&BitwardenLegacyKeyBytes> for SymmetricCryptoKey {
684    type Error = CryptoError;
685
686    fn try_from(value: &BitwardenLegacyKeyBytes) -> Result<Self, Self::Error> {
687        let slice = value.as_ref();
688
689        // Raw byte serialized keys are either 32, 64, or more bytes long. If they are 32/64, they
690        // are the raw serializations of the AES256-CBC, and AES256-CBC-HMAC keys. If they
691        // are longer, they are COSE keys. The COSE keys are padded to the minimum length of
692        // 65 bytes, when serialized to raw byte arrays.
693
694        if slice.len() == Self::AES256_CBC_HMAC_KEY_LEN || slice.len() == Self::AES256_CBC_KEY_LEN {
695            Self::try_from(EncodedSymmetricKey::BitwardenLegacyKey(value.clone()))
696        } else if slice.len() > Self::AES256_CBC_HMAC_KEY_LEN {
697            let unpadded_value = unpad_key(slice)?;
698            Ok(Self::try_from_cose(unpadded_value)?)
699        } else {
700            Err(CryptoError::InvalidKeyLen)
701        }
702    }
703}
704
705impl TryFrom<EncodedSymmetricKey> for SymmetricCryptoKey {
706    type Error = CryptoError;
707
708    fn try_from(value: EncodedSymmetricKey) -> Result<Self, Self::Error> {
709        match value {
710            EncodedSymmetricKey::BitwardenLegacyKey(key)
711                if key.as_ref().len() == Self::AES256_CBC_KEY_LEN =>
712            {
713                let mut enc_key = Box::pin(Array::<u8, U32>::default());
714                enc_key.copy_from_slice(&key.as_ref()[..Self::AES256_CBC_KEY_LEN]);
715                Ok(Self::Aes256CbcKey(Aes256CbcKey { enc_key }))
716            }
717            EncodedSymmetricKey::BitwardenLegacyKey(key)
718                if key.as_ref().len() == Self::AES256_CBC_HMAC_KEY_LEN =>
719            {
720                // The legacy byte serialization is defined as `enc_key || mac_key`
721                let mut composite_key = Box::pin(Array::<u8, U64>::default());
722                composite_key.copy_from_slice(key.as_ref());
723
724                Ok(Self::Aes256CbcHmacKey(Aes256CbcHmacKey {
725                    key: composite_key,
726                }))
727            }
728            EncodedSymmetricKey::CoseKey(key) => Self::try_from_cose(key.as_ref()),
729            _ => Err(CryptoError::InvalidKey),
730        }
731    }
732}
733
734impl CryptoKey for SymmetricCryptoKey {}
735
736// We manually implement these to make sure we don't print any sensitive data
737impl std::fmt::Debug for SymmetricCryptoKey {
738    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
739        match self {
740            SymmetricCryptoKey::Aes256CbcKey(key) => key.fmt(f),
741            SymmetricCryptoKey::Aes256CbcHmacKey(key) => key.fmt(f),
742            SymmetricCryptoKey::XChaCha20Poly1305Key(key) => key.fmt(f),
743            SymmetricCryptoKey::Aes256GcmKey(key) => key.fmt(f),
744            SymmetricCryptoKey::XAes256GcmKey(key) => key.fmt(f),
745        }
746    }
747}
748
749impl std::fmt::Debug for Aes256CbcKey {
750    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
751        let mut debug_struct = f.debug_struct("SymmetricKey::Aes256Cbc");
752        #[cfg(feature = "dangerous-crypto-debug")]
753        debug_struct.field("key", &hex::encode(self.enc_key.as_slice()));
754        debug_struct.finish()
755    }
756}
757
758impl std::fmt::Debug for Aes256CbcHmacKey {
759    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
760        let mut debug_struct = f.debug_struct("SymmetricKey::Aes256CbcHmac");
761        #[cfg(feature = "dangerous-crypto-debug")]
762        debug_struct
763            .field("enc_key", &hex::encode(self.enc_key()))
764            .field("mac_key", &hex::encode(self.mac_key()));
765        debug_struct.finish()
766    }
767}
768
769impl std::fmt::Debug for XChaCha20Poly1305Key {
770    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
771        let mut debug_struct = f.debug_struct("SymmetricKey::XChaCha20Poly1305");
772        debug_struct.field("key_id", &self.key_id);
773        debug_struct.field(
774            "supported_operations",
775            &self
776                .supported_operations
777                .iter()
778                .map(|key_operation: &KeyOperation| cose::debug_key_operation(*key_operation))
779                .collect::<Vec<_>>(),
780        );
781        #[cfg(feature = "dangerous-crypto-debug")]
782        debug_struct.field("key", &hex::encode(self.enc_key.as_slice()));
783        debug_struct.finish()
784    }
785}
786
787impl std::fmt::Debug for XAes256GcmKey {
788    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
789        let mut debug_struct = f.debug_struct("SymmetricKey::XAes256Gcm");
790        debug_struct.field("key_id", &self.key_id);
791        debug_struct.field(
792            "supported_operations",
793            &self
794                .supported_operations
795                .iter()
796                .map(|key_operation: &KeyOperation| cose::debug_key_operation(*key_operation))
797                .collect::<Vec<_>>(),
798        );
799        #[cfg(feature = "dangerous-crypto-debug")]
800        debug_struct.field("key", &hex::encode(self.enc_key.as_slice()));
801        debug_struct.finish()
802    }
803}
804
805impl std::fmt::Debug for Aes256GcmKey {
806    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
807        let mut debug_struct = f.debug_struct("SymmetricKey::Aes256Gcm");
808        debug_struct.field("key_id", &self.key_id);
809        debug_struct.field(
810            "supported_operations",
811            &self
812                .supported_operations
813                .iter()
814                .map(|key_operation: &KeyOperation| cose::debug_key_operation(*key_operation))
815                .collect::<Vec<_>>(),
816        );
817        #[cfg(feature = "dangerous-crypto-debug")]
818        debug_struct.field("key", &hex::encode(self.enc_key.as_slice()));
819        debug_struct.finish()
820    }
821}
822
823/// Pad a key to a minimum length using PKCS7-like padding.
824/// The last N bytes of the padded bytes all have the value N.
825/// For example, padded to size 4, the value 0,0 becomes 0,0,2,2.
826///
827/// COSE-serialized keys must be distinguishable from
828/// [SymmetricCryptoKey::Aes256CbcHmacKey] keys when encoded as byte arrays with no additional
829/// content format. Padding ensures that the byte representation uniquely separates keys by size.
830/// The previous key types [SymmetricCryptoKey::Aes256CbcHmacKey] and
831/// [SymmetricCryptoKey::Aes256CbcKey] are 64 and 32 bytes long respectively.
832fn pad_key(key_bytes: &mut Vec<u8>, min_length: u8) {
833    crate::keys::utils::pad_bytes(key_bytes, min_length as usize)
834        .expect("Padding cannot fail since the min_length is < 255")
835}
836
837/// Unpad a key that is padded using the PKCS7-like padding defined by [pad_key].
838/// The last N bytes of the padded bytes all have the value N.
839/// For example, padded to size 4, the value 0,0 becomes 0,0,2,2.
840///
841/// COSE-serialized keys must be distinguishable from
842/// [SymmetricCryptoKey::Aes256CbcHmacKey] keys when encoded as byte arrays with no additional
843/// content format. Padding ensures that the byte representation uniquely separates keys by size.
844/// The previous key types [SymmetricCryptoKey::Aes256CbcHmacKey] and
845/// [SymmetricCryptoKey::Aes256CbcKey] are 64 and 32 bytes long respectively.
846fn unpad_key(key_bytes: &[u8]) -> Result<&[u8], CryptoError> {
847    crate::keys::utils::unpad_bytes(key_bytes).map_err(|_| CryptoError::InvalidKey)
848}
849
850/// Encoded representation of [SymmetricCryptoKey]
851pub enum EncodedSymmetricKey {
852    /// An Aes256-CBC-HMAC key, or a Aes256-CBC key
853    BitwardenLegacyKey(BitwardenLegacyKeyBytes),
854    /// A symmetric key encoded as a COSE key
855    CoseKey(CoseKeyBytes),
856}
857impl From<EncodedSymmetricKey> for Vec<u8> {
858    fn from(val: EncodedSymmetricKey) -> Self {
859        match val {
860            EncodedSymmetricKey::BitwardenLegacyKey(key) => key.to_vec(),
861            EncodedSymmetricKey::CoseKey(key) => key.to_vec(),
862        }
863    }
864}
865impl EncodedSymmetricKey {
866    /// Returns the content format of the encoded symmetric key.
867    #[allow(private_interfaces)]
868    pub fn content_format(&self) -> ContentFormat {
869        match self {
870            EncodedSymmetricKey::BitwardenLegacyKey(_) => ContentFormat::BitwardenLegacyKey,
871            EncodedSymmetricKey::CoseKey(_) => ContentFormat::CoseKey,
872        }
873    }
874}
875
876// Note: Deserialize and Serialize are only implemented until external usages of
877// symmetric crypto keys are removed. We do not want to support these, but while
878// these have to be supported, we want to have type-safety over having raw byte
879// arrays.
880impl<'de> Deserialize<'de> for SymmetricCryptoKey {
881    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
882    where
883        D: serde::Deserializer<'de>,
884    {
885        deserializer.deserialize_str(FromStrVisitor::new())
886    }
887}
888
889impl FromStr for SymmetricCryptoKey {
890    type Err = CryptoError;
891
892    fn from_str(s: &str) -> Result<Self, Self::Err> {
893        let bytes = B64::try_from(s.to_string()).map_err(|_| CryptoError::InvalidKey)?;
894        Self::try_from(bytes).map_err(|_| CryptoError::InvalidKey)
895    }
896}
897
898impl Serialize for SymmetricCryptoKey {
899    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
900    where
901        S: serde::Serializer,
902    {
903        serializer.serialize_str(&self.to_base64().to_string())
904    }
905}
906
907/// Test only helper for deriving a symmetric key.
908#[cfg(test)]
909pub fn derive_symmetric_key(name: &str) -> Aes256CbcHmacKey {
910    use zeroize::Zeroizing;
911
912    use crate::{derive_shareable_key, generate_random_bytes};
913
914    let secret: Zeroizing<[u8; 16]> = generate_random_bytes();
915    derive_shareable_key(secret, name, None)
916}
917
918#[cfg(test)]
919mod tests {
920    use bitwarden_encoding::B64;
921    use coset::{CborSerializable, iana::KeyOperation};
922    use hybrid_array::Array;
923    use typenum::U32;
924
925    use super::{
926        AES256_CBC_HMAC_ENC_KEY_SIZE, EncodedSymmetricKey, KEY_ID_SIZE, SymmetricCryptoKey,
927        derive_symmetric_key,
928    };
929    use crate::{
930        Aes256CbcHmacKey, Aes256CbcKey, BitwardenLegacyKeyBytes, CoseKeyThumbprintExt,
931        SymmetricKeyAlgorithm, XAes256GcmKey, XChaCha20Poly1305Key,
932        keys::{
933            KeyId,
934            symmetric_crypto_key::{pad_key, unpad_key},
935        },
936    };
937
938    #[test]
939    #[ignore = "Manual test to verify debug format"]
940    fn test_key_debug() {
941        let aes_key = SymmetricCryptoKey::make_aes256_cbc_hmac_key();
942        println!("{:?}", aes_key);
943        let xchacha_key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
944        println!("{:?}", xchacha_key);
945    }
946
947    #[test]
948    fn test_serialize_deserialize_symmetric_crypto_key() {
949        let key = SymmetricCryptoKey::make_aes256_cbc_hmac_key();
950        let serialized = serde_json::to_string(&key).unwrap();
951        let deserialized: SymmetricCryptoKey = serde_json::from_str(&serialized).unwrap();
952        assert_eq!(key, deserialized);
953    }
954
955    #[test]
956    fn test_symmetric_crypto_key() {
957        let key = SymmetricCryptoKey::Aes256CbcHmacKey(derive_symmetric_key("test"));
958        let key2 = SymmetricCryptoKey::try_from(key.to_base64()).unwrap();
959
960        assert_eq!(key, key2);
961
962        let key = "UY4B5N4DA4UisCNClgZtRr6VLy9ZF5BXXC7cDZRqourKi4ghEMgISbCsubvgCkHf5DZctQjVot11/vVvN9NNHQ==".to_string();
963        let key2 = SymmetricCryptoKey::try_from(key.clone()).unwrap();
964        assert_eq!(key, key2.to_base64().to_string());
965    }
966
967    #[test]
968    fn test_encode_decode_old_symmetric_crypto_key() {
969        let key = SymmetricCryptoKey::make_aes256_cbc_hmac_key();
970        let encoded = key.to_encoded();
971        let decoded = SymmetricCryptoKey::try_from(&encoded).unwrap();
972        assert_eq!(key, decoded);
973    }
974
975    #[test]
976    fn test_decode_new_symmetric_crypto_key() {
977        let key: B64 = ("pQEEAlDib+JxbqMBlcd3KTUesbufAzoAARFvBIQDBAUGIFggt79surJXmqhPhYuuqi9ZyPfieebmtw2OsmN5SDrb4yUB").parse()
978        .unwrap();
979        let key = BitwardenLegacyKeyBytes::from(&key);
980        let key = SymmetricCryptoKey::try_from(&key).unwrap();
981        match key {
982            SymmetricCryptoKey::XChaCha20Poly1305Key(_) => (),
983            _ => panic!("Invalid key type"),
984        }
985    }
986
987    #[test]
988    fn test_encode_xchacha20_poly1305_key() {
989        let key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
990        let encoded = key.to_encoded();
991        let decoded = SymmetricCryptoKey::try_from(&encoded).unwrap();
992        assert_eq!(key, decoded);
993    }
994
995    #[test]
996    fn test_pad_unpad_key_63() {
997        let original_key = vec![1u8; 63];
998        let mut key_bytes = original_key.clone();
999        let mut encoded_bytes = vec![1u8; 65];
1000        encoded_bytes[63] = 2;
1001        encoded_bytes[64] = 2;
1002        pad_key(&mut key_bytes, 65);
1003        assert_eq!(encoded_bytes, key_bytes);
1004        let unpadded_key = unpad_key(&key_bytes).unwrap();
1005        assert_eq!(original_key, unpadded_key);
1006    }
1007
1008    #[test]
1009    fn test_pad_unpad_key_64() {
1010        let original_key = vec![1u8; 64];
1011        let mut key_bytes = original_key.clone();
1012        let mut encoded_bytes = vec![1u8; 65];
1013        encoded_bytes[64] = 1;
1014        pad_key(&mut key_bytes, 65);
1015        assert_eq!(encoded_bytes, key_bytes);
1016        let unpadded_key = unpad_key(&key_bytes).unwrap();
1017        assert_eq!(original_key, unpadded_key);
1018    }
1019
1020    #[test]
1021    fn test_pad_unpad_key_65() {
1022        let original_key = vec![1u8; 65];
1023        let mut key_bytes = original_key.clone();
1024        let mut encoded_bytes = vec![1u8; 66];
1025        encoded_bytes[65] = 1;
1026        pad_key(&mut key_bytes, 65);
1027        assert_eq!(encoded_bytes, key_bytes);
1028        let unpadded_key = unpad_key(&key_bytes).unwrap();
1029        assert_eq!(original_key, unpadded_key);
1030    }
1031
1032    #[test]
1033    fn test_eq_aes_cbc_hmac() {
1034        let key1 = SymmetricCryptoKey::make_aes256_cbc_hmac_key();
1035        let key2 = SymmetricCryptoKey::make_aes256_cbc_hmac_key();
1036        assert_ne!(key1, key2);
1037        let key3 = SymmetricCryptoKey::try_from(key1.to_base64()).unwrap();
1038        assert_eq!(key1, key3);
1039    }
1040
1041    #[test]
1042    fn test_eq_aes_cbc() {
1043        let key1 =
1044            SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(vec![1u8; 32])).unwrap();
1045        let key2 =
1046            SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(vec![2u8; 32])).unwrap();
1047        assert_ne!(key1, key2);
1048        let key3 = SymmetricCryptoKey::try_from(key1.to_base64()).unwrap();
1049        assert_eq!(key1, key3);
1050    }
1051
1052    #[test]
1053    fn test_eq_xchacha20_poly1305() {
1054        let key1 = SymmetricCryptoKey::make_xchacha20_poly1305_key();
1055        let key2 = SymmetricCryptoKey::make_xchacha20_poly1305_key();
1056        assert_ne!(key1, key2);
1057        let key3 = SymmetricCryptoKey::try_from(key1.to_base64()).unwrap();
1058        assert_eq!(key1, key3);
1059    }
1060
1061    #[test]
1062    fn test_neq_different_key_types() {
1063        let key1 = SymmetricCryptoKey::Aes256CbcKey(Aes256CbcKey {
1064            enc_key: Box::pin(Array::<u8, U32>::default()),
1065        });
1066        let key2 = SymmetricCryptoKey::XChaCha20Poly1305Key(XChaCha20Poly1305Key {
1067            enc_key: Box::pin(Array::<u8, U32>::default()),
1068            key_id: KeyId::from([0; 16]),
1069            supported_operations: vec![
1070                KeyOperation::Decrypt,
1071                KeyOperation::Encrypt,
1072                KeyOperation::WrapKey,
1073                KeyOperation::UnwrapKey,
1074            ],
1075        });
1076        assert_ne!(key1, key2);
1077    }
1078
1079    #[test]
1080    fn test_eq_variant_aes256_cbc() {
1081        let key1 = Aes256CbcKey {
1082            enc_key: Box::pin(Array::from([1u8; 32])),
1083        };
1084        let key2 = Aes256CbcKey {
1085            enc_key: Box::pin(Array::from([1u8; 32])),
1086        };
1087        let key3 = Aes256CbcKey {
1088            enc_key: Box::pin(Array::from([2u8; 32])),
1089        };
1090        assert_eq!(key1, key2);
1091        assert_ne!(key1, key3);
1092    }
1093
1094    #[test]
1095    fn test_eq_variant_aes256_cbc_hmac() {
1096        let key1 = Aes256CbcHmacKey::new(&[1u8; 32], &[2u8; 32]);
1097        let key2 = Aes256CbcHmacKey::new(&[1u8; 32], &[2u8; 32]);
1098        let key3 = Aes256CbcHmacKey::new(&[3u8; 32], &[4u8; 32]);
1099        assert_eq!(key1, key2);
1100        assert_ne!(key1, key3);
1101    }
1102
1103    #[test]
1104    fn test_eq_variant_xchacha20_poly1305() {
1105        let key1 = XChaCha20Poly1305Key {
1106            enc_key: Box::pin(Array::from([1u8; 32])),
1107            key_id: KeyId::from([0; 16]),
1108            supported_operations: vec![
1109                KeyOperation::Decrypt,
1110                KeyOperation::Encrypt,
1111                KeyOperation::WrapKey,
1112                KeyOperation::UnwrapKey,
1113            ],
1114        };
1115        let key2 = XChaCha20Poly1305Key {
1116            enc_key: Box::pin(Array::from([1u8; 32])),
1117            key_id: KeyId::from([0; 16]),
1118            supported_operations: vec![
1119                KeyOperation::Decrypt,
1120                KeyOperation::Encrypt,
1121                KeyOperation::WrapKey,
1122                KeyOperation::UnwrapKey,
1123            ],
1124        };
1125        let key3 = XChaCha20Poly1305Key {
1126            enc_key: Box::pin(Array::from([2u8; 32])),
1127            key_id: KeyId::from([1; 16]),
1128            supported_operations: vec![
1129                KeyOperation::Decrypt,
1130                KeyOperation::Encrypt,
1131                KeyOperation::WrapKey,
1132                KeyOperation::UnwrapKey,
1133            ],
1134        };
1135        assert_eq!(key1, key2);
1136        assert_ne!(key1, key3);
1137    }
1138
1139    fn fixed_xaes_key_inner() -> XAes256GcmKey {
1140        XAes256GcmKey {
1141            enc_key: Box::pin(Array::from([
1142                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
1143                0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
1144                0x1c, 0x1d, 0x1e, 0x1f,
1145            ])),
1146            key_id: KeyId::from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
1147            supported_operations: vec![KeyOperation::Encrypt, KeyOperation::Decrypt],
1148        }
1149    }
1150
1151    fn fixed_xaes_key() -> SymmetricCryptoKey {
1152        SymmetricCryptoKey::XAes256GcmKey(fixed_xaes_key_inner())
1153    }
1154
1155    #[test]
1156    fn test_make_xaes256_gcm_key() {
1157        assert!(matches!(
1158            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XAes256Gcm),
1159            SymmetricCryptoKey::XAes256GcmKey(_)
1160        ));
1161    }
1162
1163    #[test]
1164    fn test_xaes256_gcm_encoding_roundtrips() {
1165        const PADDED_KEY: &str = "pQEEAlAAAQIDBAUGBwgJCgsMDQ4PAzoAARF5BIIDBCBYIAABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fAQ==";
1166
1167        let key = fixed_xaes_key();
1168        assert_eq!(key.to_base64().to_string(), PADDED_KEY);
1169        let padded = SymmetricCryptoKey::try_from(PADDED_KEY.to_owned()).unwrap();
1170        assert_eq!(padded, key);
1171        let SymmetricCryptoKey::XAes256GcmKey(ref padded) = padded else {
1172            panic!("expected XAES-256-GCM key");
1173        };
1174        assert_eq!(
1175            padded.supported_operations,
1176            [KeyOperation::Encrypt, KeyOperation::Decrypt]
1177        );
1178
1179        let EncodedSymmetricKey::CoseKey(raw) = key.to_encoded_raw() else {
1180            panic!("expected COSE key encoding");
1181        };
1182        assert_eq!(
1183            SymmetricCryptoKey::try_from_cose(raw.as_ref()).unwrap(),
1184            key
1185        );
1186
1187        let cose_key = coset::CoseKey::from_slice(raw.as_ref()).unwrap();
1188        assert_eq!(
1189            cose_key.alg,
1190            Some(coset::Algorithm::PrivateUse(crate::cose::XAES_256_GCM))
1191        );
1192        assert_eq!(cose_key.key_id, (0u8..16).collect::<Vec<_>>());
1193        assert_eq!(cose_key.key_ops.len(), 2);
1194        assert!(
1195            cose_key
1196                .key_ops
1197                .contains(&coset::RegisteredLabel::Assigned(KeyOperation::Encrypt))
1198        );
1199        assert!(
1200            cose_key
1201                .key_ops
1202                .contains(&coset::RegisteredLabel::Assigned(KeyOperation::Decrypt))
1203        );
1204    }
1205
1206    #[test]
1207    fn test_xaes256_gcm_equality() {
1208        let key = fixed_xaes_key();
1209        let same = fixed_xaes_key();
1210        assert_eq!(key, same);
1211
1212        let mut different_bytes = fixed_xaes_key_inner();
1213        different_bytes.enc_key[0] ^= 1;
1214        assert_ne!(key, SymmetricCryptoKey::XAes256GcmKey(different_bytes));
1215
1216        let mut different_id = fixed_xaes_key_inner();
1217        different_id.key_id = KeyId::from([1; 16]);
1218        assert_ne!(key, SymmetricCryptoKey::XAes256GcmKey(different_id));
1219
1220        for other in [
1221            SymmetricCryptoKey::Aes256CbcKey(Aes256CbcKey {
1222                enc_key: Box::pin(Array::default()),
1223            }),
1224            SymmetricCryptoKey::Aes256CbcHmacKey(Aes256CbcHmacKey::new(&[0u8; 32], &[0u8; 32])),
1225            SymmetricCryptoKey::Aes256GcmKey(crate::Aes256GcmKey::make()),
1226            SymmetricCryptoKey::XChaCha20Poly1305Key(XChaCha20Poly1305Key::make()),
1227        ] {
1228            assert_ne!(key, other);
1229        }
1230    }
1231
1232    #[test]
1233    fn test_neq_different_key_id() {
1234        let key1 = XChaCha20Poly1305Key {
1235            enc_key: Box::pin(Array::<u8, U32>::default()),
1236            key_id: KeyId::from([0; 16]),
1237            supported_operations: vec![
1238                KeyOperation::Decrypt,
1239                KeyOperation::Encrypt,
1240                KeyOperation::WrapKey,
1241                KeyOperation::UnwrapKey,
1242            ],
1243        };
1244        let key2 = XChaCha20Poly1305Key {
1245            enc_key: Box::pin(Array::<u8, U32>::default()),
1246            key_id: KeyId::from([1; 16]),
1247            supported_operations: vec![
1248                KeyOperation::Decrypt,
1249                KeyOperation::Encrypt,
1250                KeyOperation::WrapKey,
1251                KeyOperation::UnwrapKey,
1252            ],
1253        };
1254        assert_ne!(key1, key2);
1255
1256        let key1 = SymmetricCryptoKey::XChaCha20Poly1305Key(key1);
1257        let key2 = SymmetricCryptoKey::XChaCha20Poly1305Key(key2);
1258        assert_ne!(key1, key2);
1259    }
1260
1261    const AES256_GCM_KEY: &str =
1262        "pQEEAlACAgICAgICAgICAgICAgICAwMEhAMEBQYgWCABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=";
1263    const AES256_GCM_KEY_THUMBPRINT: &str =
1264        "3810c7275ee292caca13d938a057a94c75210087d960d3eb6868c0ffe99b5643";
1265
1266    const XCHACHA20_POLY1305_KEY: &str = "pQEEAlDib+JxbqMBlcd3KTUesbufAzoAARFvBIQDBAUGIFggt79surJXmqhPhYuuqi9ZyPfieebmtw2OsmN5SDrb4yUB";
1267    const XCHACHA20_POLY1305_KEY_THUMBPRINT: &str =
1268        "64aec2d09ef5ba8b310ef9a70346b03422443e295b6f045e38169ae97e579d85";
1269
1270    #[test]
1271    fn test_decode_new_aes256_gcm_key() {
1272        let key: B64 = AES256_GCM_KEY.parse().unwrap();
1273        let key = SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(&key)).unwrap();
1274        match key {
1275            SymmetricCryptoKey::Aes256GcmKey(_) => (),
1276            _ => panic!("Invalid key type"),
1277        }
1278    }
1279
1280    #[test]
1281    fn test_thumbprint_aes256_gcm_vector() {
1282        // A fixed AES-256-GCM COSE key.
1283        let key: B64 = AES256_GCM_KEY.parse().unwrap();
1284        let key = SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(&key)).unwrap();
1285        assert_eq!(
1286            key.thumbprint().unwrap().to_hex(),
1287            AES256_GCM_KEY_THUMBPRINT
1288        );
1289    }
1290
1291    #[test]
1292    fn test_thumbprint_xchacha20_poly1305_vector() {
1293        // A fixed XChaCha20Poly1305 COSE key.
1294        let key: B64 = XCHACHA20_POLY1305_KEY.parse().unwrap();
1295        let key = SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(&key)).unwrap();
1296        assert_eq!(
1297            key.thumbprint().unwrap().to_hex(),
1298            XCHACHA20_POLY1305_KEY_THUMBPRINT
1299        );
1300    }
1301
1302    #[test]
1303    fn test_thumbprint_is_deterministic() {
1304        let key = SymmetricCryptoKey::make_xchacha20_poly1305_key();
1305        assert_eq!(key.thumbprint().unwrap(), key.thumbprint().unwrap());
1306    }
1307
1308    /// The unauthenticated AES-CBC key is the only variant with no COSE key view, and so the only
1309    /// one without a thumbprint.
1310    #[test]
1311    fn test_thumbprint_errors_for_unauthenticated_aes_cbc() {
1312        let key = SymmetricCryptoKey::Aes256CbcKey(Aes256CbcKey {
1313            enc_key: Box::pin(Array::from([1u8; 32])),
1314        });
1315        assert!(key.thumbprint().is_err());
1316    }
1317
1318    const AES256_CBC_HMAC_KEY_THUMBPRINT: &str =
1319        "ac4ecffb2e087a59180d1dd19950b8e9e634997f47bbfd7a2bb829edf7a9f900";
1320    const AES256_CBC_HMAC_KEY_ID: &str = "ac4ecffb2e087a59180d1dd19950b8e9";
1321
1322    /// A fixed AES-256-CBC-HMAC key: `enc_key` is `0x00..0x1f`, `mac_key` is `0x20..0x3f`.
1323    fn fixed_aes_cbc_hmac_key_inner() -> Aes256CbcHmacKey {
1324        Aes256CbcHmacKey::new(
1325            &std::array::from_fn(|i| i as u8),
1326            &std::array::from_fn(|i| (i + 32) as u8),
1327        )
1328    }
1329
1330    fn fixed_aes_cbc_hmac_key() -> SymmetricCryptoKey {
1331        SymmetricCryptoKey::Aes256CbcHmacKey(fixed_aes_cbc_hmac_key_inner())
1332    }
1333
1334    #[test]
1335    #[ignore = "Generates test vectors; run manually"]
1336    fn generate_aes256_cbc_hmac_thumbprint_vectors() {
1337        let key = fixed_aes_cbc_hmac_key();
1338        println!(
1339            "const AES256_CBC_HMAC_KEY_THUMBPRINT: &str = \"{}\";",
1340            key.thumbprint().unwrap().to_hex()
1341        );
1342        println!(
1343            "const AES256_CBC_HMAC_KEY_ID: &str = \"{}\";",
1344            hex::encode(key.key_id().unwrap().as_slice())
1345        );
1346    }
1347
1348    /// Locks in the thumbprint of an AES-256-CBC-HMAC key: the RFC 9679 thumbprint of a COSE
1349    /// `Symmetric` key whose `k` is the 64-byte `enc_key || mac_key` composite. The derived key ID
1350    /// depends on this, so it must never change.
1351    #[test]
1352    fn test_thumbprint_aes256_cbc_hmac_vector() {
1353        assert_eq!(
1354            fixed_aes_cbc_hmac_key().thumbprint().unwrap().to_hex(),
1355            AES256_CBC_HMAC_KEY_THUMBPRINT
1356        );
1357    }
1358
1359    #[test]
1360    fn test_key_id_aes256_cbc_hmac_vector() {
1361        let key_id = fixed_aes_cbc_hmac_key().key_id().unwrap();
1362        assert_eq!(hex::encode(key_id.as_slice()), AES256_CBC_HMAC_KEY_ID);
1363    }
1364
1365    /// Locks in the derivation rule itself: the key ID is the leading `KEY_ID_SIZE` bytes of the
1366    /// key's thumbprint.
1367    #[test]
1368    fn test_key_id_is_thumbprint_prefix() {
1369        let key = fixed_aes_cbc_hmac_key();
1370        let thumbprint = key.thumbprint().unwrap();
1371        assert_eq!(
1372            key.key_id().unwrap().as_slice(),
1373            &thumbprint.as_bytes()[..KEY_ID_SIZE]
1374        );
1375    }
1376
1377    #[test]
1378    fn test_key_id_aes256_cbc_hmac_is_deterministic() {
1379        assert_eq!(
1380            fixed_aes_cbc_hmac_key().key_id(),
1381            fixed_aes_cbc_hmac_key().key_id()
1382        );
1383    }
1384
1385    /// Both halves of the key must feed the ID, or two keys differing only in their MAC key would
1386    /// collide.
1387    #[test]
1388    fn test_key_id_aes256_cbc_hmac_covers_both_halves() {
1389        let key = fixed_aes_cbc_hmac_key();
1390
1391        // Flip the first byte of the encryption half, then of the MAC half.
1392        let mut different_enc = fixed_aes_cbc_hmac_key_inner();
1393        different_enc.key[0] ^= 1;
1394        assert_ne!(
1395            key.key_id(),
1396            SymmetricCryptoKey::Aes256CbcHmacKey(different_enc).key_id()
1397        );
1398
1399        let mut different_mac = fixed_aes_cbc_hmac_key_inner();
1400        different_mac.key[AES256_CBC_HMAC_ENC_KEY_SIZE] ^= 1;
1401        assert_ne!(
1402            key.key_id(),
1403            SymmetricCryptoKey::Aes256CbcHmacKey(different_mac).key_id()
1404        );
1405    }
1406
1407    /// Having a COSE key view must not change how these keys are serialized: they remain the raw
1408    /// 64-byte legacy encoding. Changing this would break every existing user key.
1409    #[test]
1410    fn test_aes256_cbc_hmac_still_encodes_as_legacy_64_bytes() {
1411        let key = fixed_aes_cbc_hmac_key();
1412
1413        let EncodedSymmetricKey::BitwardenLegacyKey(raw) = key.to_encoded_raw() else {
1414            panic!("expected legacy key encoding");
1415        };
1416        assert_eq!(raw.as_ref().len(), 64);
1417        assert_eq!(raw.as_ref(), (0u8..64).collect::<Vec<_>>());
1418
1419        assert_eq!(key.to_encoded().as_ref().len(), 64);
1420        assert_eq!(SymmetricCryptoKey::try_from(key.to_base64()).unwrap(), key);
1421    }
1422}