1use std::{borrow::Cow, str::FromStr};
2
3use bitwarden_encoding::{B64, FromStrVisitor};
4use coset::{CborSerializable, iana::KeyOperation};
5use rand::RngExt;
6use serde::Deserialize;
7
8use super::{check_length, from_b64, from_b64_vec, split_enc_string};
9use crate::{
10 Aes256CbcHmacKey, ContentFormat, CoseEncrypt0Bytes, KeyDecryptable, KeyEncryptable,
11 KeyEncryptableWithContentType, SymmetricCryptoKey, SymmetricKeyAlgorithm, Utf8Bytes,
12 XAes256GcmKey, XChaCha20Poly1305Key,
13 cose::{XAES_256_GCM, XCHACHA20_POLY1305, symmetric::CoseContentEncryptionAlgorithm},
14 error::{CryptoError, EncStringParseError, Result, UnsupportedOperationError},
15 hazmat::symmetric_encryption::Aes256CbcHmacSha256,
16 keys::KeyId,
17};
18
19#[cfg(feature = "wasm")]
20#[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
21const TS_CUSTOM_TYPES: &'static str = r#"
22export type EncString = Tagged<string, "EncString">;
23"#;
24
25const AES256_CBC_TYPE: u8 = 0;
28const AES256_CBC_HMAC_TYPE: u8 = 2;
29const COSE_ENCRYPT0_TYPE: u8 = 7;
30
31#[allow(missing_docs)]
68#[derive(Clone, zeroize::ZeroizeOnDrop, PartialEq)]
69#[allow(unused, non_camel_case_types)]
70pub enum EncString {
71 Aes256Cbc_B64 {
73 iv: [u8; 16],
74 data: Vec<u8>,
75 },
76 Aes256Cbc_HmacSha256_B64 {
79 iv: [u8; 16],
80 mac: [u8; 32],
81 data: Vec<u8>,
82 },
83 Cose_Encrypt0_B64 {
85 data: Vec<u8>,
86 },
87 Unparseable {
90 raw: String,
91 },
92}
93
94bitwarden_ffi::impl_wire_string!(EncString);
95
96#[cfg(feature = "wasm")]
97impl TryFrom<wasm_bindgen::JsValue> for EncString {
98 type Error = CryptoError;
99
100 fn try_from(value: wasm_bindgen::JsValue) -> Result<Self, Self::Error> {
101 let string = value
102 .as_string()
103 .ok_or(EncStringParseError::NoType)
104 .map_err(CryptoError::from)?;
105 Self::from_str(&string)
106 }
107}
108
109impl FromStr for EncString {
111 type Err = CryptoError;
112
113 fn from_str(s: &str) -> Result<Self, Self::Err> {
116 Ok(Self::parse_known_format(s)
117 .unwrap_or_else(|| EncString::Unparseable { raw: s.to_owned() }))
118 }
119}
120
121impl From<&str> for EncString {
124 fn from(s: &str) -> Self {
125 Self::parse_known_format(s).unwrap_or_else(|| EncString::Unparseable { raw: s.to_owned() })
126 }
127}
128
129impl From<String> for EncString {
132 fn from(s: String) -> Self {
133 Self::parse_known_format(&s).unwrap_or(EncString::Unparseable { raw: s })
134 }
135}
136
137impl EncString {
138 fn parse_known_format(s: &str) -> Option<Self> {
140 let (enc_type, parts) = split_enc_string(s);
141 match (enc_type, parts.len()) {
142 ("0", 2) => Some(EncString::Aes256Cbc_B64 {
143 iv: from_b64(parts[0]).ok()?,
144 data: from_b64_vec(parts[1]).ok()?,
145 }),
146 ("2", 3) => Some(EncString::Aes256Cbc_HmacSha256_B64 {
147 iv: from_b64(parts[0]).ok()?,
148 data: from_b64_vec(parts[1]).ok()?,
149 mac: from_b64(parts[2]).ok()?,
150 }),
151 ("7", 1) => Some(EncString::Cose_Encrypt0_B64 {
152 data: from_b64_vec(parts[0]).ok()?,
153 }),
154 _ => None,
155 }
156 }
157
158 pub fn parse_strict(s: &str) -> Result<Self, CryptoError> {
160 Self::parse_known_format(s).ok_or(CryptoError::UnparseableEncString)
161 }
162
163 pub fn key_id(&self) -> Option<KeyId> {
166 let EncString::Cose_Encrypt0_B64 { data } = self else {
167 return None;
168 };
169
170 let msg = coset::CoseEncrypt0::from_slice(data.as_slice()).ok()?;
171 KeyId::try_from(msg.protected.header.key_id.as_slice()).ok()
172 }
173
174 pub fn algorithm(&self) -> Option<SymmetricKeyAlgorithm> {
177 let data = match self {
178 EncString::Aes256Cbc_HmacSha256_B64 { .. } => {
179 return Some(SymmetricKeyAlgorithm::Aes256CbcHmac);
180 }
181 EncString::Cose_Encrypt0_B64 { data } => data,
182 EncString::Aes256Cbc_B64 { .. } | EncString::Unparseable { .. } => return None,
183 };
184
185 let msg = coset::CoseEncrypt0::from_slice(data.as_slice()).ok()?;
186 let algorithm = msg.protected.header.alg.as_ref()?;
187 let algorithm = match CoseContentEncryptionAlgorithm::try_from(algorithm).ok()? {
188 CoseContentEncryptionAlgorithm::Aes256Gcm => SymmetricKeyAlgorithm::Aes256Gcm,
189 CoseContentEncryptionAlgorithm::XAes256Gcm => SymmetricKeyAlgorithm::XAes256Gcm,
190 CoseContentEncryptionAlgorithm::XChaCha20Poly1305 => {
191 SymmetricKeyAlgorithm::XChaCha20Poly1305
192 }
193 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead => {
194 SymmetricKeyAlgorithm::Aes256CbcHmac
195 }
196 };
197 Some(algorithm)
198 }
199
200 pub fn try_from_optional(s: Option<String>) -> Result<Option<EncString>, CryptoError> {
202 s.map(|s| s.parse()).transpose()
203 }
204
205 pub fn from_buffer(buf: &[u8]) -> Result<Self> {
208 if buf.is_empty() {
209 return Err(EncStringParseError::NoType.into());
210 }
211 let enc_type = buf[0];
212
213 match enc_type {
214 AES256_CBC_TYPE => {
215 check_length(buf, 18)?;
216 let iv = buf[1..17].try_into().expect("Valid length");
217 let data = buf[17..].to_vec();
218
219 Ok(EncString::Aes256Cbc_B64 { iv, data })
220 }
221 AES256_CBC_HMAC_TYPE => {
222 check_length(buf, 50)?;
223 let iv = buf[1..17].try_into().expect("Valid length");
224 let mac = buf[17..49].try_into().expect("Valid length");
225 let data = buf[49..].to_vec();
226
227 Ok(EncString::Aes256Cbc_HmacSha256_B64 { iv, mac, data })
228 }
229 COSE_ENCRYPT0_TYPE => Ok(EncString::Cose_Encrypt0_B64 {
230 data: buf[1..].to_vec(),
231 }),
232 _ => Err(EncStringParseError::InvalidTypeSymm {
233 enc_type: enc_type.to_string(),
234 parts: 1,
235 }
236 .into()),
237 }
238 }
239
240 #[allow(missing_docs)]
241 pub fn to_buffer(&self) -> Result<Vec<u8>> {
242 let mut buf;
243 let enc_type = self.enc_type().ok_or(CryptoError::UnparseableEncString)?;
244
245 match self {
246 EncString::Aes256Cbc_B64 { iv, data } => {
247 buf = Vec::with_capacity(1 + 16 + data.len());
248 buf.push(enc_type);
249 buf.extend_from_slice(iv);
250 buf.extend_from_slice(data);
251 }
252 EncString::Aes256Cbc_HmacSha256_B64 { iv, mac, data } => {
253 buf = Vec::with_capacity(1 + 16 + 32 + data.len());
254 buf.push(enc_type);
255 buf.extend_from_slice(iv);
256 buf.extend_from_slice(mac);
257 buf.extend_from_slice(data);
258 }
259 EncString::Cose_Encrypt0_B64 { data } => {
260 buf = Vec::with_capacity(1 + data.len());
261 buf.push(enc_type);
262 buf.extend_from_slice(data);
263 }
264 EncString::Unparseable { .. } => return Err(CryptoError::UnparseableEncString),
265 }
266
267 Ok(buf)
268 }
269}
270
271#[allow(clippy::to_string_trait_impl)]
276impl ToString for EncString {
277 fn to_string(&self) -> String {
278 fn fmt_parts(enc_type: u8, parts: &[&[u8]]) -> String {
279 let encoded_parts: Vec<String> = parts
280 .iter()
281 .map(|part| B64::from(*part).to_string())
282 .collect();
283 format!("{}.{}", enc_type, encoded_parts.join("|"))
284 }
285
286 match &self {
287 EncString::Aes256Cbc_B64 { iv, data } => fmt_parts(AES256_CBC_TYPE, &[iv, data]),
288 EncString::Aes256Cbc_HmacSha256_B64 { iv, mac, data } => {
289 fmt_parts(AES256_CBC_HMAC_TYPE, &[iv, data, mac])
290 }
291 EncString::Cose_Encrypt0_B64 { data } => fmt_parts(COSE_ENCRYPT0_TYPE, &[data]),
292 EncString::Unparseable { raw } => raw.clone(),
293 }
294 }
295}
296
297impl std::fmt::Debug for EncString {
298 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
299 match self {
300 EncString::Aes256Cbc_B64 { iv, data } => {
301 let mut debug_struct = f.debug_struct("EncString::Aes256Cbc");
302 #[cfg(feature = "dangerous-crypto-debug")]
303 {
304 debug_struct.field("iv", &hex::encode(iv));
305 debug_struct.field("data", &hex::encode(data));
306 }
307 #[cfg(not(feature = "dangerous-crypto-debug"))]
308 {
309 _ = iv;
310 _ = data;
311 }
312 debug_struct.finish()
313 }
314 EncString::Aes256Cbc_HmacSha256_B64 { iv, mac, data } => {
315 let mut debug_struct = f.debug_struct("EncString::Aes256CbcHmacSha256");
316 #[cfg(feature = "dangerous-crypto-debug")]
317 {
318 debug_struct.field("iv", &hex::encode(iv));
319 debug_struct.field("data", &hex::encode(data));
320 debug_struct.field("mac", &hex::encode(mac));
321 }
322 #[cfg(not(feature = "dangerous-crypto-debug"))]
323 {
324 _ = iv;
325 _ = data;
326 _ = mac;
327 }
328 debug_struct.finish()
329 }
330 EncString::Unparseable { raw } => {
331 let mut debug_struct = f.debug_struct("EncString::Unparseable");
332 #[cfg(feature = "dangerous-crypto-debug")]
333 debug_struct.field("raw", raw);
334 #[cfg(not(feature = "dangerous-crypto-debug"))]
335 {
336 _ = raw;
337 }
338 debug_struct.finish()
339 }
340 EncString::Cose_Encrypt0_B64 { data } => {
341 let mut debug_struct = f.debug_struct("EncString::CoseEncrypt0");
342
343 match coset::CoseEncrypt0::from_slice(data.as_slice()) {
344 Ok(msg) => {
345 if let Some(ref alg) = msg.protected.header.alg {
346 let alg_name = match alg {
347 coset::Algorithm::PrivateUse(XCHACHA20_POLY1305) => {
348 "XChaCha20-Poly1305"
349 }
350 coset::Algorithm::PrivateUse(XAES_256_GCM) => "XAES-256-GCM",
351 other => return debug_struct.field("algorithm", other).finish(),
352 };
353 debug_struct.field("algorithm", &alg_name);
354 }
355
356 let key_id = &msg.protected.header.key_id;
357 if let Ok(key_id) = KeyId::try_from(key_id.as_slice()) {
358 debug_struct.field("key_id", &key_id);
359 }
360 debug_struct.field("nonce", &hex::encode(msg.unprotected.iv.as_slice()));
361 if let Some(ref content_type) = msg.protected.header.content_type {
362 debug_struct.field("content_type", content_type);
363 }
364
365 #[cfg(feature = "dangerous-crypto-debug")]
366 if let Some(ref ciphertext) = msg.ciphertext {
367 debug_struct.field("ciphertext", &hex::encode(ciphertext));
368 }
369 }
370 Err(_) => {
371 debug_struct.field("error", &"INVALID_COSE");
372 }
373 }
374
375 debug_struct.finish()
376 }
377 }
378 }
379}
380
381impl<'de> Deserialize<'de> for EncString {
382 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
383 where
384 D: serde::Deserializer<'de>,
385 {
386 deserializer.deserialize_str(FromStrVisitor::new())
387 }
388}
389
390impl serde::Serialize for EncString {
391 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
392 where
393 S: serde::Serializer,
394 {
395 serializer.serialize_str(&self.to_string())
396 }
397}
398
399impl EncString {
400 pub(crate) fn encrypt_aes256_hmac(
401 data_dec: &[u8],
402 key: &Aes256CbcHmacKey,
403 ) -> Result<EncString> {
404 let mut iv = [0u8; 16];
405 bitwarden_random::rng().fill(&mut iv);
406 let (mac, data) = Aes256CbcHmacSha256::encrypt(&iv, data_dec, key.as_composite_key());
407 Ok(EncString::Aes256Cbc_HmacSha256_B64 { iv, mac, data })
408 }
409
410 pub(crate) fn encrypt_xchacha20_poly1305(
411 data_dec: &[u8],
412 key: &XChaCha20Poly1305Key,
413 content_format: ContentFormat,
414 ) -> Result<EncString> {
415 let data =
416 crate::cose::symmetric::encrypt_xchacha20_poly1305(data_dec, key, content_format)?;
417 Ok(EncString::Cose_Encrypt0_B64 {
418 data: data.to_vec(),
419 })
420 }
421
422 pub(crate) fn encrypt_xaes256_gcm(
423 data_dec: &[u8],
424 key: &XAes256GcmKey,
425 content_format: ContentFormat,
426 ) -> Result<EncString> {
427 let data = crate::cose::symmetric::encrypt_xaes256_gcm(data_dec, key, content_format)?;
428 Ok(EncString::Cose_Encrypt0_B64 {
429 data: data.to_vec(),
430 })
431 }
432
433 const fn enc_type(&self) -> Option<u8> {
436 match self {
437 EncString::Aes256Cbc_B64 { .. } => Some(AES256_CBC_TYPE),
438 EncString::Aes256Cbc_HmacSha256_B64 { .. } => Some(AES256_CBC_HMAC_TYPE),
439 EncString::Cose_Encrypt0_B64 { .. } => Some(COSE_ENCRYPT0_TYPE),
440 EncString::Unparseable { .. } => None,
441 }
442 }
443}
444
445impl KeyEncryptableWithContentType<SymmetricCryptoKey, EncString> for &[u8] {
446 fn encrypt_with_key(
447 self,
448 key: &SymmetricCryptoKey,
449 content_format: ContentFormat,
450 ) -> Result<EncString> {
451 match key {
452 SymmetricCryptoKey::Aes256CbcHmacKey(key) => EncString::encrypt_aes256_hmac(self, key),
453 SymmetricCryptoKey::XChaCha20Poly1305Key(inner_key) => {
454 if !inner_key
455 .supported_operations
456 .contains(&KeyOperation::Encrypt)
457 {
458 return Err(CryptoError::KeyOperationNotSupported(KeyOperation::Encrypt));
459 }
460 EncString::encrypt_xchacha20_poly1305(self, inner_key, content_format)
461 }
462 SymmetricCryptoKey::XAes256GcmKey(key) => {
463 if !key.supported_operations.contains(&KeyOperation::Encrypt) {
464 return Err(CryptoError::KeyOperationNotSupported(KeyOperation::Encrypt));
465 }
466 EncString::encrypt_xaes256_gcm(self, key, content_format)
467 }
468 SymmetricCryptoKey::Aes256CbcKey(_) => Err(CryptoError::OperationNotSupported(
469 UnsupportedOperationError::EncryptionNotImplementedForKey,
470 )),
471 SymmetricCryptoKey::Aes256GcmKey(_) => Err(CryptoError::OperationNotSupported(
472 UnsupportedOperationError::EncryptionNotImplementedForKey,
473 )),
474 }
475 }
476}
477
478impl KeyDecryptable<SymmetricCryptoKey, Vec<u8>> for EncString {
479 fn decrypt_with_key(&self, key: &SymmetricCryptoKey) -> Result<Vec<u8>> {
480 match (self, key) {
481 (EncString::Aes256Cbc_B64 { .. }, SymmetricCryptoKey::Aes256CbcKey(_)) => {
482 Err(CryptoError::OperationNotSupported(
483 UnsupportedOperationError::DecryptionNotImplementedForKey,
484 ))
485 }
486 (
487 EncString::Aes256Cbc_HmacSha256_B64 { iv, mac, data },
488 SymmetricCryptoKey::Aes256CbcHmacKey(key),
489 ) => Aes256CbcHmacSha256::decrypt(iv, data, mac, key.as_composite_key())
490 .map_err(|_| CryptoError::Decrypt),
491 (
492 EncString::Cose_Encrypt0_B64 { data },
493 SymmetricCryptoKey::XChaCha20Poly1305Key(key),
494 ) => {
495 let (decrypted_message, _) = crate::cose::symmetric::decrypt_xchacha20_poly1305(
496 &CoseEncrypt0Bytes::from(data.as_slice()),
497 key,
498 )?;
499 Ok(decrypted_message)
500 }
501 (EncString::Cose_Encrypt0_B64 { data }, SymmetricCryptoKey::XAes256GcmKey(key)) => {
502 let (decrypted, _) = crate::cose::symmetric::decrypt_xaes256_gcm(
503 &CoseEncrypt0Bytes::from(data.as_slice()),
504 key,
505 )?;
506 Ok(decrypted)
507 }
508 (EncString::Cose_Encrypt0_B64 { data }, SymmetricCryptoKey::Aes256CbcHmacKey(key)) => {
509 let (decrypted, _) = crate::cose::symmetric::decrypt_aes256_cbc_hmac_aead(
510 &CoseEncrypt0Bytes::from(data.as_slice()),
511 key,
512 )?;
513 Ok(decrypted)
514 }
515 (EncString::Unparseable { .. }, _) => Err(CryptoError::UnparseableEncString),
516 (_, SymmetricCryptoKey::XAes256GcmKey(_)) => Err(CryptoError::WrongKeyType),
517 _ => Err(CryptoError::WrongKeyType),
518 }
519 }
520}
521
522impl KeyEncryptable<SymmetricCryptoKey, EncString> for String {
523 fn encrypt_with_key(self, key: &SymmetricCryptoKey) -> Result<EncString> {
524 Utf8Bytes::from(self).encrypt_with_key(key)
525 }
526}
527
528impl KeyEncryptable<SymmetricCryptoKey, EncString> for &str {
529 fn encrypt_with_key(self, key: &SymmetricCryptoKey) -> Result<EncString> {
530 Utf8Bytes::from(self).encrypt_with_key(key)
531 }
532}
533
534impl KeyDecryptable<SymmetricCryptoKey, String> for EncString {
535 #[bitwarden_logging::instrument(err)]
536 fn decrypt_with_key(&self, key: &SymmetricCryptoKey) -> Result<String> {
537 let dec: Vec<u8> = self.decrypt_with_key(key)?;
538 String::from_utf8(dec).map_err(|_| CryptoError::InvalidUtf8String)
539 }
540}
541
542impl schemars::JsonSchema for EncString {
545 fn schema_name() -> Cow<'static, str> {
546 "EncString".into()
547 }
548
549 fn json_schema(generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
550 generator.subschema_for::<String>()
551 }
552}
553
554#[cfg(test)]
555mod tests {
556 use coset::iana::KeyOperation;
557 use schemars::schema_for;
558
559 use super::EncString;
560 use crate::{
561 Aes256CbcHmacKey, ContentFormat, CryptoError, KEY_ID_SIZE, KeyDecryptable, KeyEncryptable,
562 SymmetricCryptoKey, SymmetricKeyAlgorithm,
563 cose::symmetric::{CoseContentEncryptionAlgorithm, encrypt_cose0},
564 derive_symmetric_key,
565 };
566
567 const AES256_CBC_HMAC_COSE_PLAINTEXT: &str = "Type 7 AES-256-CBC-HMAC test vector";
568 const AES256_CBC_HMAC_COSE_ENC_STRING: &str = "7.g1g/owE6AAERegN4I2FwcGxpY2F0aW9uL3guYml0d2FyZGVuLnV0ZjgtcGFkZGVkBFCsTs/7Lgh6WRgNHdGZULjpoQVQXYJbsJat2eG+9CcclU7mqVhwKiZITE/+y7LqmpX+A+QS7iZ3Ng/0/+zZnW/TFQ//5t5qnJl6p0GV3t804h4rSfwEGtXvI27//Uaup0KEq+XU8kwx5m4VSq8JarD48spPgxlrmpLncTpFgIh+Z6YDPc300PsAbOj+bHT+dSLFH7cRHA==";
569
570 fn aes_cbc_hmac_key() -> Aes256CbcHmacKey {
572 Aes256CbcHmacKey::new(
573 &std::array::from_fn(|i| i as u8),
574 &std::array::from_fn(|i| (i + 32) as u8),
575 )
576 }
577
578 fn xaes_key(operations: Vec<KeyOperation>) -> SymmetricCryptoKey {
579 SymmetricCryptoKey::XAes256GcmKey(crate::XAes256GcmKey {
580 key_id: [0u8; KEY_ID_SIZE].into(),
581 enc_key: Box::pin([0u8; 32].into()),
582 supported_operations: operations,
583 })
584 }
585
586 fn encrypt_with_xaes(plaintext: &str) -> EncString {
587 plaintext
588 .to_owned()
589 .encrypt_with_key(&xaes_key(vec![
590 coset::iana::KeyOperation::Decrypt,
591 coset::iana::KeyOperation::Encrypt,
592 coset::iana::KeyOperation::WrapKey,
593 coset::iana::KeyOperation::UnwrapKey,
594 ]))
595 .expect("encryption works")
596 }
597
598 fn encrypt_with_xchacha20(plaintext: &str) -> EncString {
599 let key_id = [0u8; KEY_ID_SIZE];
600 let enc_key = [0u8; 32];
601 let key = SymmetricCryptoKey::XChaCha20Poly1305Key(crate::XChaCha20Poly1305Key {
602 key_id: key_id.into(),
603 enc_key: Box::pin(enc_key.into()),
604 supported_operations: vec![
605 coset::iana::KeyOperation::Decrypt,
606 coset::iana::KeyOperation::Encrypt,
607 coset::iana::KeyOperation::WrapKey,
608 coset::iana::KeyOperation::UnwrapKey,
609 ],
610 });
611
612 plaintext.encrypt_with_key(&key).expect("encryption works")
613 }
614
615 #[test]
616 fn test_key_id_of_cose_enc_string() {
617 let enc_string = encrypt_with_xaes("Test key id");
618 assert_eq!(enc_string.key_id(), Some([0u8; KEY_ID_SIZE].into()));
619 }
620
621 #[test]
622 fn test_algorithm_of_enc_string() {
623 let v1 = EncString::encrypt_aes256_hmac(b"Test", &derive_symmetric_key("test")).unwrap();
624 assert_eq!(v1.algorithm(), Some(SymmetricKeyAlgorithm::Aes256CbcHmac));
625 assert_eq!(
626 encrypt_with_xaes("Test").algorithm(),
627 Some(SymmetricKeyAlgorithm::XAes256Gcm)
628 );
629 assert_eq!(
630 encrypt_with_xchacha20("Test").algorithm(),
631 Some(SymmetricKeyAlgorithm::XChaCha20Poly1305)
632 );
633 }
634
635 #[test]
636 fn test_key_id_of_legacy_enc_string_is_none() {
637 let enc_string =
638 EncString::encrypt_aes256_hmac(b"Test key id", &derive_symmetric_key("test")).unwrap();
639 assert_eq!(enc_string.key_id(), None);
640 }
641
642 #[test]
643 #[ignore = "Manual test to verify debug format"]
644 fn test_debug() {
645 let enc_string = encrypt_with_xchacha20("Test debug string");
646 println!("{:?}", enc_string);
647 let enc_string_aes =
648 EncString::encrypt_aes256_hmac(b"Test debug string", &derive_symmetric_key("test"))
649 .unwrap();
650 println!("{:?}", enc_string_aes);
651 }
652
653 #[test]
657 fn test_xchacha20_encstring_string_padding_block_sizes() {
658 let cases = [
659 ("", 32), (&"a".repeat(31), 32), (&"a".repeat(32), 64), (&"a".repeat(63), 64), (&"a".repeat(64), 96), ];
665
666 let ciphertext_lengths: Vec<_> = cases
667 .iter()
668 .map(|(plaintext, _)| encrypt_with_xchacha20(plaintext).to_string().len())
669 .collect();
670
671 assert_eq!(ciphertext_lengths[0], ciphertext_lengths[1]);
673 assert_ne!(ciphertext_lengths[1], ciphertext_lengths[2]);
675 assert_eq!(ciphertext_lengths[2], ciphertext_lengths[3]);
676 assert_ne!(ciphertext_lengths[3], ciphertext_lengths[4]);
678 }
679
680 #[test]
681 fn test_enc_roundtrip_xchacha20() {
682 let key_id = [0u8; KEY_ID_SIZE];
683 let enc_key = [0u8; 32];
684 let key = SymmetricCryptoKey::XChaCha20Poly1305Key(crate::XChaCha20Poly1305Key {
685 key_id: key_id.into(),
686 enc_key: Box::pin(enc_key.into()),
687 supported_operations: vec![
688 coset::iana::KeyOperation::Decrypt,
689 coset::iana::KeyOperation::Encrypt,
690 coset::iana::KeyOperation::WrapKey,
691 coset::iana::KeyOperation::UnwrapKey,
692 ],
693 });
694
695 let test_string = "encrypted_test_string";
696 let cipher = test_string.to_owned().encrypt_with_key(&key).unwrap();
697 let decrypted_str: String = cipher.decrypt_with_key(&key).unwrap();
698 assert_eq!(decrypted_str, test_string);
699 }
700
701 #[test]
702 fn test_xaes_encstring_string_roundtrips() {
703 let key = xaes_key(vec![
704 coset::iana::KeyOperation::Decrypt,
705 coset::iana::KeyOperation::Encrypt,
706 coset::iana::KeyOperation::WrapKey,
707 coset::iana::KeyOperation::UnwrapKey,
708 ]);
709 for plaintext in ["", "encrypted_test_string"] {
710 let encrypted = plaintext.to_owned().encrypt_with_key(&key).unwrap();
711 let decrypted: String = encrypted.decrypt_with_key(&key).unwrap();
712 assert_eq!(decrypted, plaintext);
713 }
714 }
715
716 #[test]
717 fn test_xaes_encstring_string_padding_block_sizes() {
718 let lengths = [0, 31, 32, 63, 64]
727 .map(|length| encrypt_with_xaes(&"a".repeat(length)).to_string().len());
728
729 assert_eq!(lengths[0], lengths[1]); assert_ne!(lengths[1], lengths[2]); assert_eq!(lengths[2], lengths[3]); assert_ne!(lengths[3], lengths[4]); }
734
735 #[test]
736 fn test_xaes_encryption_requires_encrypt_operation() {
737 assert!(matches!(
738 "plaintext"
739 .to_owned()
740 .encrypt_with_key(&xaes_key(vec![KeyOperation::Decrypt])),
741 Err(CryptoError::KeyOperationNotSupported(KeyOperation::Encrypt))
742 ));
743 }
744
745 #[test]
746 fn test_xaes_rejects_unsupported_encstring_variant() {
747 let encrypted =
748 EncString::encrypt_aes256_hmac(b"plaintext", &derive_symmetric_key("wrapping key"))
749 .unwrap();
750 let result: Result<Vec<u8>, CryptoError> =
751 encrypted.decrypt_with_key(&xaes_key(vec![KeyOperation::Encrypt]));
752 assert!(matches!(result, Err(CryptoError::WrongKeyType)));
753 }
754
755 #[test]
756 fn test_xaes_encstring_debug_is_readable() {
757 let debug = format!("{:?}", encrypt_with_xaes("plaintext"));
758 assert!(debug.contains("EncString::CoseEncrypt0"));
759 assert!(debug.contains("XAES-256-GCM"));
760 assert!(debug.contains("KeyId(00000000000000000000000000000000)"));
761 assert!(debug.contains("nonce"));
762 assert!(debug.contains("content_type"));
763 }
764
765 #[test]
766 fn test_enc_string_roundtrip() {
767 let key = SymmetricCryptoKey::Aes256CbcHmacKey(derive_symmetric_key("test"));
768
769 let test_string = "encrypted_test_string";
770 let cipher = test_string.to_string().encrypt_with_key(&key).unwrap();
771
772 let decrypted_str: String = cipher.decrypt_with_key(&key).unwrap();
773 assert_eq!(decrypted_str, test_string);
774 }
775
776 #[test]
777 fn test_enc_roundtrip_xchacha20_empty() {
778 let key_id = [0u8; KEY_ID_SIZE];
779 let enc_key = [0u8; 32];
780 let key = SymmetricCryptoKey::XChaCha20Poly1305Key(crate::XChaCha20Poly1305Key {
781 key_id: key_id.into(),
782 enc_key: Box::pin(enc_key.into()),
783 supported_operations: vec![
784 coset::iana::KeyOperation::Decrypt,
785 coset::iana::KeyOperation::Encrypt,
786 coset::iana::KeyOperation::WrapKey,
787 coset::iana::KeyOperation::UnwrapKey,
788 ],
789 });
790
791 let test_string = "";
792 let cipher = test_string.to_owned().encrypt_with_key(&key).unwrap();
793 let decrypted_str: String = cipher.decrypt_with_key(&key).unwrap();
794 assert_eq!(decrypted_str, test_string);
795 }
796
797 #[test]
798 fn test_enc_string_roundtrip_empty() {
799 let key = SymmetricCryptoKey::Aes256CbcHmacKey(derive_symmetric_key("test"));
800
801 let test_string = "";
802 let cipher = test_string.to_string().encrypt_with_key(&key).unwrap();
803
804 let decrypted_str: String = cipher.decrypt_with_key(&key).unwrap();
805 assert_eq!(decrypted_str, test_string);
806 }
807
808 #[test]
809 fn test_enc_string_ref_roundtrip() {
810 let key = SymmetricCryptoKey::Aes256CbcHmacKey(derive_symmetric_key("test"));
811
812 let test_string: &'static str = "encrypted_test_string";
813 let cipher = test_string.to_string().encrypt_with_key(&key).unwrap();
814
815 let decrypted_str: String = cipher.decrypt_with_key(&key).unwrap();
816 assert_eq!(decrypted_str, test_string);
817 }
818
819 #[test]
820 fn test_enc_string_serialization() {
821 #[derive(serde::Serialize, serde::Deserialize)]
822 struct Test {
823 key: EncString,
824 }
825
826 let cipher = "2.pMS6/icTQABtulw52pq2lg==|XXbxKxDTh+mWiN1HjH2N1w==|Q6PkuT+KX/axrgN9ubD5Ajk2YNwxQkgs3WJM0S0wtG8=";
827 let serialized = format!("{{\"key\":\"{cipher}\"}}");
828
829 let t = serde_json::from_str::<Test>(&serialized).unwrap();
830 assert_eq!(t.key.enc_type(), Some(2));
831 assert_eq!(t.key.to_string(), cipher);
832 assert_eq!(serde_json::to_string(&t).unwrap(), serialized);
833 }
834
835 #[test]
836 fn test_enc_from_to_buffer() {
837 let enc_str: &str = "2.pMS6/icTQABtulw52pq2lg==|XXbxKxDTh+mWiN1HjH2N1w==|Q6PkuT+KX/axrgN9ubD5Ajk2YNwxQkgs3WJM0S0wtG8=";
838 let enc_string: EncString = enc_str.parse().unwrap();
839
840 let enc_buf = enc_string.to_buffer().unwrap();
841
842 assert_eq!(
843 enc_buf,
844 vec![
845 2, 164, 196, 186, 254, 39, 19, 64, 0, 109, 186, 92, 57, 218, 154, 182, 150, 67,
846 163, 228, 185, 63, 138, 95, 246, 177, 174, 3, 125, 185, 176, 249, 2, 57, 54, 96,
847 220, 49, 66, 72, 44, 221, 98, 76, 209, 45, 48, 180, 111, 93, 118, 241, 43, 16, 211,
848 135, 233, 150, 136, 221, 71, 140, 125, 141, 215
849 ]
850 );
851
852 let enc_string_new = EncString::from_buffer(&enc_buf).unwrap();
853
854 assert_eq!(enc_string_new.to_string(), enc_str)
855 }
856
857 #[test]
858 fn test_from_str_cbc256() {
859 let enc_str = "0.pMS6/icTQABtulw52pq2lg==|XXbxKxDTh+mWiN1HjH2N1w==";
860 let enc_string: EncString = enc_str.parse().unwrap();
861
862 assert_eq!(enc_string.enc_type(), Some(0));
863 if let EncString::Aes256Cbc_B64 { iv, data } = &enc_string {
864 assert_eq!(
865 iv,
866 &[
867 164, 196, 186, 254, 39, 19, 64, 0, 109, 186, 92, 57, 218, 154, 182, 150
868 ]
869 );
870 assert_eq!(
871 data,
872 &[
873 93, 118, 241, 43, 16, 211, 135, 233, 150, 136, 221, 71, 140, 125, 141, 215
874 ]
875 );
876 } else {
877 panic!("Invalid variant")
878 };
879 }
880
881 #[test]
882 fn test_decrypt_fails_for_cbc256_keys() {
883 let key = "hvBMMb1t79YssFZkpetYsM3deyVuQv4r88Uj9gvYe08=".to_string();
884 let key = SymmetricCryptoKey::try_from(key).unwrap();
885
886 let enc_str = "0.NQfjHLr6za7VQVAbrpL81w==|wfrjmyJ0bfwkQlySrhw8dA==";
887 let enc_string: EncString = enc_str.parse().unwrap();
888 assert_eq!(enc_string.enc_type(), Some(0));
889
890 let result: Result<String, CryptoError> = enc_string.decrypt_with_key(&key);
891 assert!(
892 matches!(
893 result,
894 Err(CryptoError::OperationNotSupported(
895 crate::error::UnsupportedOperationError::DecryptionNotImplementedForKey
896 )),
897 ),
898 "Expected decrypt to fail when using deprecated type 0 key",
899 );
900 }
901
902 #[test]
903 fn test_decrypt_downgrade_encstring_prevention() {
904 let key = "hvBMMb1t79YssFZkpetYsM3deyVuQv4r88Uj9gvYe0+G8EwxvW3v1iywVmSl61iwzd17JW5C/ivzxSP2C9h7Tw==".to_string();
907 let key = SymmetricCryptoKey::try_from(key).unwrap();
908
909 let enc_str = "0.NQfjHLr6za7VQVAbrpL81w==|wfrjmyJ0bfwkQlySrhw8dA==";
913 let enc_string: EncString = enc_str.parse().unwrap();
914 assert_eq!(enc_string.enc_type(), Some(0));
915
916 let result: Result<String, CryptoError> = enc_string.decrypt_with_key(&key);
917 assert!(matches!(result, Err(CryptoError::WrongKeyType)));
918 }
919
920 #[test]
921 fn test_encrypt_fails_when_operation_not_allowed() {
922 let key_id = [0u8; KEY_ID_SIZE];
924 let enc_key = [0u8; 32];
925 let key = SymmetricCryptoKey::XChaCha20Poly1305Key(crate::XChaCha20Poly1305Key {
926 key_id: key_id.into(),
927 enc_key: Box::pin(enc_key.into()),
928 supported_operations: vec![KeyOperation::Decrypt],
929 });
930
931 let plaintext = "should fail";
932 let result = plaintext.encrypt_with_key(&key);
933 assert!(
934 matches!(
935 result,
936 Err(CryptoError::KeyOperationNotSupported(KeyOperation::Encrypt))
937 ),
938 "Expected encrypt to fail with KeyOperationNotSupported, got: {result:?}"
939 );
940 }
941
942 #[test]
945 fn test_from_str_unparseable_roundtrips() {
946 let cases = [
947 "2.AAECAw==|Y3Q=|AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=", "2.AAECAwQFBgcICQoLDA0ODw==|Y3Q=|AAECAw==", "0.AAECAw==|Y3Q=", "2.!!!!|Y3Q=|AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=", "8.ABC", "7.ABC|DEF", ];
954
955 for enc_str in cases {
956 let enc_string: EncString = enc_str.parse().expect("parsing never fails");
957 assert!(
958 matches!(enc_string, EncString::Unparseable { .. }),
959 "Expected {enc_str} to parse as unparseable",
960 );
961 assert_eq!(enc_string.to_string(), enc_str);
962 assert_eq!(enc_string.enc_type(), None);
963 }
964 }
965
966 #[test]
967 fn test_from_string_and_str() {
968 let known = "2.pMS6/icTQABtulw52pq2lg==|XXbxKxDTh+mWiN1HjH2N1w==|Q6PkuT+KX/axrgN9ubD5Ajk2YNwxQkgs3WJM0S0wtG8=";
969 let unknown = "8.ABC";
970
971 assert_eq!(EncString::from(known).enc_type(), Some(2));
972 assert_eq!(EncString::from(known.to_owned()).enc_type(), Some(2));
973
974 assert!(matches!(
975 EncString::from(unknown),
976 EncString::Unparseable { .. }
977 ));
978 assert_eq!(EncString::from(unknown.to_owned()).to_string(), unknown);
979 }
980
981 #[test]
982 fn test_parse_strict_rejects_unparseable() {
983 let cases = [
984 "2.AAECAw==|Y3Q=|AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=", "2.AAECAwQFBgcICQoLDA0ODw==|Y3Q=|AAECAw==", "8.ABC", ];
988
989 for enc_str in cases {
990 assert!(
991 matches!(
992 EncString::parse_strict(enc_str),
993 Err(CryptoError::UnparseableEncString)
994 ),
995 "Expected {enc_str} to be rejected",
996 );
997 }
998 }
999
1000 #[test]
1001 fn test_parse_strict_accepts_known_formats() {
1002 let enc_str = "2.pMS6/icTQABtulw52pq2lg==|XXbxKxDTh+mWiN1HjH2N1w==|Q6PkuT+KX/axrgN9ubD5Ajk2YNwxQkgs3WJM0S0wtG8=";
1003 let enc_string = EncString::parse_strict(enc_str).unwrap();
1004
1005 assert_eq!(enc_string.enc_type(), Some(2));
1006 assert_eq!(enc_string.to_string(), enc_str);
1007 }
1008
1009 #[test]
1010 fn test_unparseable_serde_roundtrip() {
1011 #[derive(serde::Serialize, serde::Deserialize)]
1012 struct Test {
1013 key: EncString,
1014 }
1015
1016 let cipher = "2.AAECAw==|Y3Q=|AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=";
1017 let serialized = format!("{{\"key\":\"{cipher}\"}}");
1018
1019 let t = serde_json::from_str::<Test>(&serialized).unwrap();
1020 assert!(matches!(t.key, EncString::Unparseable { .. }));
1021 assert_eq!(serde_json::to_string(&t).unwrap(), serialized);
1022 }
1023
1024 #[test]
1025 fn test_unparseable_decrypt_fails() {
1026 let key = SymmetricCryptoKey::Aes256CbcHmacKey(derive_symmetric_key("test"));
1027 let enc_string: EncString = "2.AAECAw==|Y3Q=|AAECAw==".parse().unwrap();
1028
1029 let result: Result<Vec<u8>, CryptoError> = enc_string.decrypt_with_key(&key);
1030 assert!(matches!(result, Err(CryptoError::UnparseableEncString)));
1031 }
1032
1033 #[test]
1034 fn test_unparseable_to_buffer_fails() {
1035 let enc_string: EncString = "2.AAECAw==|Y3Q=|AAECAw==".parse().unwrap();
1036
1037 assert!(matches!(
1038 enc_string.to_buffer(),
1039 Err(CryptoError::UnparseableEncString)
1040 ));
1041 }
1042
1043 #[test]
1044 fn test_from_buffer_stays_strict() {
1045 assert!(EncString::from_buffer(&[]).is_err());
1046 assert!(EncString::from_buffer(&[2, 0, 0]).is_err());
1047 assert!(EncString::from_buffer(&[8, 0, 0]).is_err());
1048 }
1049
1050 #[test]
1051 #[cfg(not(feature = "dangerous-crypto-debug"))]
1052 fn test_debug_format() {
1053 let enc_str = "2.pMS6/icTQABtulw52pq2lg==|XXbxKxDTh+mWiN1HjH2N1w==|Q6PkuT+KX/axrgN9ubD5Ajk2YNwxQkgs3WJM0S0wtG8=";
1054 let enc_string: EncString = enc_str.parse().unwrap();
1055 assert_eq!(
1056 "EncString::Aes256CbcHmacSha256".to_string(),
1057 format!("{:?}", enc_string)
1058 );
1059 }
1060
1061 #[test]
1062 #[ignore = "Generates test vectors; run manually"]
1063 fn generate_aes256_cbc_hmac_cose_test_vector() {
1064 let key = aes_cbc_hmac_key();
1065 let protected_header = coset::HeaderBuilder::from(ContentFormat::Utf8)
1066 .key_id(key.key_id().as_slice().to_vec())
1067 .build();
1068 let message = encrypt_cose0(
1069 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead,
1070 coset::CoseEncrypt0Builder::new(),
1071 protected_header,
1072 AES256_CBC_HMAC_COSE_PLAINTEXT.as_bytes(),
1073 key.as_composite_key(),
1074 )
1075 .unwrap();
1076 let enc_string = EncString::Cose_Encrypt0_B64 {
1077 data: coset::CborSerializable::to_vec(message).unwrap(),
1078 };
1079 println!(
1080 "const AES256_CBC_HMAC_COSE_ENC_STRING: &str = \"{}\";",
1081 enc_string.to_string()
1082 );
1083 }
1084
1085 #[test]
1088 fn test_decrypt_aes256_cbc_hmac_cose_test_vector() {
1089 let key = SymmetricCryptoKey::Aes256CbcHmacKey(aes_cbc_hmac_key());
1090 let enc_string: EncString = AES256_CBC_HMAC_COSE_ENC_STRING.parse().unwrap();
1091
1092 assert_eq!(
1093 enc_string.algorithm(),
1094 Some(SymmetricKeyAlgorithm::Aes256CbcHmac)
1095 );
1096 assert_eq!(enc_string.key_id(), key.key_id());
1097
1098 let decrypted: String = enc_string.decrypt_with_key(&key).unwrap();
1099 assert_eq!(decrypted, AES256_CBC_HMAC_COSE_PLAINTEXT);
1100 }
1101
1102 #[test]
1103 fn test_decrypt_aes256_cbc_hmac_cose_wrong_key() {
1104 let key = SymmetricCryptoKey::Aes256CbcHmacKey(derive_symmetric_key("other"));
1105 let enc_string: EncString = AES256_CBC_HMAC_COSE_ENC_STRING.parse().unwrap();
1106
1107 let result: Result<String, _> = enc_string.decrypt_with_key(&key);
1108 assert!(matches!(result, Err(CryptoError::WrongCoseKeyId)));
1109 }
1110
1111 #[test]
1112 fn test_json_schema() {
1113 let schema = schema_for!(EncString);
1114
1115 assert_eq!(
1116 serde_json::to_string(&schema).unwrap(),
1117 r#"{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"EncString","type":"string"}"#
1118 );
1119 }
1120}