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