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#[derive(Clone, Copy, Debug, PartialEq)]
60pub enum SymmetricKeyAlgorithm {
61 Aes256CbcHmac,
63 XChaCha20Poly1305,
65 Aes256Gcm,
72 XAes256Gcm,
75}
76
77#[derive(ZeroizeOnDrop, Clone)]
81pub struct Aes256CbcKey {
82 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
98pub(crate) const AES256_CBC_HMAC_ENC_KEY_SIZE: usize = 32;
100pub(crate) const AES256_CBC_HMAC_MAC_KEY_SIZE: usize = 32;
102pub(crate) const AES256_CBC_HMAC_KEY_SIZE: usize =
104 AES256_CBC_HMAC_ENC_KEY_SIZE + AES256_CBC_HMAC_MAC_KEY_SIZE;
105
106#[derive(ZeroizeOnDrop, Clone)]
109pub struct Aes256CbcHmacKey {
110 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 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 pub(crate) fn as_composite_key(&self) -> &[u8; AES256_CBC_HMAC_KEY_SIZE] {
147 &self.key.0
148 }
149
150 pub(crate) fn as_slice(&self) -> &[u8] {
152 self.key.as_slice()
153 }
154
155 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 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 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
186fn 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#[derive(Zeroize, Clone)]
213pub struct XChaCha20Poly1305Key {
214 pub(crate) key_id: KeyId,
215 pub(crate) enc_key: Pin<Box<Array<u8, U32>>>,
216 #[zeroize(skip)]
221 pub(crate) supported_operations: Vec<KeyOperation>,
222}
223
224impl XChaCha20Poly1305Key {
225 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#[derive(Zeroize, Clone)]
259pub struct Aes256GcmKey {
260 pub(crate) key_id: KeyId,
261 pub(crate) enc_key: Pin<Box<Array<u8, U32>>>,
262 #[zeroize(skip)]
265 pub(crate) supported_operations: Vec<KeyOperation>,
266}
267
268impl Aes256GcmKey {
269 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#[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 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
347pub(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 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 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#[derive(ZeroizeOnDrop, Clone)]
395pub enum SymmetricCryptoKey {
396 #[allow(missing_docs)]
397 Aes256CbcKey(Aes256CbcKey),
398 #[allow(missing_docs)]
399 Aes256CbcHmacKey(Aes256CbcHmacKey),
400 XChaCha20Poly1305Key(XChaCha20Poly1305Key),
403 Aes256GcmKey(Aes256GcmKey),
406 XAes256GcmKey(XAes256GcmKey),
409}
410
411impl SymmetricCryptoKey {
412 const AES256_CBC_KEY_LEN: usize = 32;
414 const AES256_CBC_HMAC_KEY_LEN: usize = 64;
416
417 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 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 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 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 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 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); BitwardenLegacyKeyBytes::from(encoded_key)
485 }
486 }
487 }
488
489 #[cfg(test)]
492 pub fn generate_seeded_for_unit_tests(seed: &str) -> Self {
493 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 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 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 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 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 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 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 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 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
735impl 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
822fn 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
836fn unpad_key(key_bytes: &[u8]) -> Result<&[u8], CryptoError> {
846 crate::keys::utils::unpad_bytes(key_bytes).map_err(|_| CryptoError::InvalidKey)
847}
848
849pub enum EncodedSymmetricKey {
851 BitwardenLegacyKey(BitwardenLegacyKeyBytes),
853 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 #[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
875impl<'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#[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 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 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 #[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 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 #[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 #[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 #[test]
1387 fn test_key_id_aes256_cbc_hmac_covers_both_halves() {
1388 let key = fixed_aes_cbc_hmac_key();
1389
1390 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 #[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}