1use coset::{
7 Algorithm, CborSerializable, CoseEncrypt, CoseEncrypt0, CoseEncrypt0Builder,
8 CoseEncryptBuilder, Header, HeaderBuilder, iana,
9};
10
11use super::{AES_256_CBC_HMAC_SHA256_AEAD, XAES_256_GCM, XCHACHA20_POLY1305};
12use crate::{
13 Aes256CbcHmacKey, ContentFormat, CoseEncrypt0Bytes, CryptoError, XAes256GcmKey,
14 XChaCha20Poly1305Key,
15 error::EncStringParseError,
16 hazmat::symmetric_encryption::{
17 Aead,
18 aes_gcm::{Aes256Gcm, Aes256GcmCiphertext, Aes256GcmNonce},
19 aes256_cbc_hmac_sha256_aead::{
20 Aes256CbcHmacSha256Aead, Aes256CbcHmacSha256AeadCiphertext,
21 Aes256CbcHmacSha256AeadNonce,
22 },
23 xaes_256_gcm::{XAes256Gcm, XAes256GcmCiphertext, XAes256GcmNonce},
24 xchacha20::{XChaCha20Poly1305, XChaCha20Poly1305Ciphertext, XChaCha20Poly1305Nonce},
25 },
26};
27
28const TEXT_PAD_BLOCK_SIZE: usize = 32;
29
30fn should_pad_content(format: &ContentFormat) -> bool {
31 matches!(format, ContentFormat::Utf8)
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub(crate) enum CoseContentEncryptionAlgorithm {
41 Aes256Gcm,
43 XAes256Gcm,
45 XChaCha20Poly1305,
47 Aes256CbcHmacSha256Aead,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub(crate) enum CoseAlgorithmPolicy {
54 RequireProtectedHeaderAlgorithm,
56 Exactly(CoseContentEncryptionAlgorithm),
58 ProtectedHeaderAlgorithmOrLegacyDefault(CoseContentEncryptionAlgorithm),
60}
61
62impl TryFrom<&Algorithm> for CoseContentEncryptionAlgorithm {
63 type Error = CryptoError;
64
65 fn try_from(algorithm: &Algorithm) -> Result<Self, Self::Error> {
66 match algorithm {
67 Algorithm::Assigned(iana::Algorithm::A256GCM) => Ok(Self::Aes256Gcm),
68 Algorithm::PrivateUse(XAES_256_GCM) => Ok(Self::XAes256Gcm),
69 Algorithm::PrivateUse(XCHACHA20_POLY1305) => Ok(Self::XChaCha20Poly1305),
70 Algorithm::PrivateUse(AES_256_CBC_HMAC_SHA256_AEAD) => {
71 Ok(Self::Aes256CbcHmacSha256Aead)
72 }
73 _ => Err(CryptoError::WrongKeyType),
74 }
75 }
76}
77
78fn algorithm_from_header(
86 header: &Header,
87 policy: CoseAlgorithmPolicy,
88) -> Result<CoseContentEncryptionAlgorithm, CryptoError> {
89 let declared = header
90 .alg
91 .as_ref()
92 .map(CoseContentEncryptionAlgorithm::try_from)
93 .transpose()?;
94
95 match (policy, declared) {
96 (CoseAlgorithmPolicy::ProtectedHeaderAlgorithmOrLegacyDefault(default), None) => {
97 Ok(default)
98 }
99 (_, None) => Err(CryptoError::EncString(
100 EncStringParseError::CoseMissingAlgorithm,
101 )),
102 (CoseAlgorithmPolicy::Exactly(expected), Some(actual)) if actual != expected => {
103 Err(CryptoError::WrongKeyType)
104 }
105 (_, Some(actual)) => Ok(actual),
106 }
107}
108
109fn ensure_algorithm_matches<C: CoseEncryptCipher>(header: &Header) -> Result<(), CryptoError> {
116 match header.alg.as_ref() {
117 Some(algorithm) if algorithm != &C::COSE_ALGORITHM => Err(CryptoError::WrongKeyType),
118 _ => Ok(()),
119 }
120}
121
122pub(crate) fn encrypt_cose(
134 algorithm: CoseContentEncryptionAlgorithm,
135 builder: CoseEncryptBuilder,
136 protected_header: Header,
137 plaintext: &[u8],
138 cek: &[u8],
139) -> Result<CoseEncrypt, CryptoError> {
140 let mut plaintext = plaintext.to_vec();
141 if let Ok(content_format) = ContentFormat::try_from(&protected_header)
142 && should_pad_content(&content_format)
143 {
144 let min_length = TEXT_PAD_BLOCK_SIZE * (1 + (plaintext.len() / TEXT_PAD_BLOCK_SIZE));
145 crate::keys::utils::pad_bytes(&mut plaintext, min_length)?;
146 }
147 match algorithm {
148 CoseContentEncryptionAlgorithm::Aes256Gcm => {
149 let cek: &<Aes256Gcm as Aead>::Key =
150 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
151 Ok(Aes256Gcm::encrypt_cose(
152 builder,
153 protected_header,
154 &plaintext,
155 cek,
156 ))
157 }
158 CoseContentEncryptionAlgorithm::XAes256Gcm => {
159 let cek: &<XAes256Gcm as Aead>::Key =
160 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
161 Ok(XAes256Gcm::encrypt_cose(
162 builder,
163 protected_header,
164 &plaintext,
165 cek,
166 ))
167 }
168 CoseContentEncryptionAlgorithm::XChaCha20Poly1305 => {
169 let cek: &<XChaCha20Poly1305 as Aead>::Key =
170 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
171 Ok(XChaCha20Poly1305::encrypt_cose(
172 builder,
173 protected_header,
174 &plaintext,
175 cek,
176 ))
177 }
178 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead => {
179 let cek: &<Aes256CbcHmacSha256Aead as Aead>::Key =
180 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
181 Ok(Aes256CbcHmacSha256Aead::encrypt_cose(
182 builder,
183 protected_header,
184 &plaintext,
185 cek,
186 ))
187 }
188 }
189}
190
191pub(crate) fn decrypt_cose(
197 cose_encrypt: &CoseEncrypt,
198 policy: CoseAlgorithmPolicy,
199 cek: &[u8],
200) -> Result<Vec<u8>, CryptoError> {
201 let decrypted = match algorithm_from_header(&cose_encrypt.protected.header, policy)? {
202 CoseContentEncryptionAlgorithm::Aes256Gcm => {
203 let cek: &<Aes256Gcm as Aead>::Key =
204 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
205 Aes256Gcm::decrypt_cose(cose_encrypt, cek)?
206 }
207 CoseContentEncryptionAlgorithm::XAes256Gcm => {
208 let cek: &<XAes256Gcm as Aead>::Key =
209 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
210 XAes256Gcm::decrypt_cose(cose_encrypt, cek)?
211 }
212 CoseContentEncryptionAlgorithm::XChaCha20Poly1305 => {
213 let cek: &<XChaCha20Poly1305 as Aead>::Key =
214 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
215 XChaCha20Poly1305::decrypt_cose(cose_encrypt, cek)?
216 }
217 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead => {
218 let cek: &<Aes256CbcHmacSha256Aead as Aead>::Key =
219 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
220 Aes256CbcHmacSha256Aead::decrypt_cose(cose_encrypt, cek)?
221 }
222 };
223 if let Ok(content_format) = ContentFormat::try_from(&cose_encrypt.protected.header)
224 && should_pad_content(&content_format)
225 {
226 return Ok(crate::keys::utils::unpad_bytes(&decrypted)?.to_vec());
227 }
228 Ok(decrypted)
229}
230
231pub(crate) fn encrypt_cose0(
238 algorithm: CoseContentEncryptionAlgorithm,
239 builder: CoseEncrypt0Builder,
240 protected_header: Header,
241 plaintext: &[u8],
242 cek: &[u8],
243) -> Result<CoseEncrypt0, CryptoError> {
244 let mut plaintext = plaintext.to_vec();
245 if let Ok(content_format) = ContentFormat::try_from(&protected_header)
246 && should_pad_content(&content_format)
247 {
248 let min_length = TEXT_PAD_BLOCK_SIZE * (1 + (plaintext.len() / TEXT_PAD_BLOCK_SIZE));
249 crate::keys::utils::pad_bytes(&mut plaintext, min_length)?;
250 }
251 match algorithm {
252 CoseContentEncryptionAlgorithm::Aes256Gcm => {
253 let cek: &<Aes256Gcm as Aead>::Key =
254 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
255 Ok(Aes256Gcm::encrypt_cose0(
256 builder,
257 protected_header,
258 &plaintext,
259 cek,
260 ))
261 }
262 CoseContentEncryptionAlgorithm::XAes256Gcm => {
263 let cek: &<XAes256Gcm as Aead>::Key =
264 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
265 Ok(XAes256Gcm::encrypt_cose0(
266 builder,
267 protected_header,
268 &plaintext,
269 cek,
270 ))
271 }
272 CoseContentEncryptionAlgorithm::XChaCha20Poly1305 => {
273 let cek: &<XChaCha20Poly1305 as Aead>::Key =
274 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
275 Ok(XChaCha20Poly1305::encrypt_cose0(
276 builder,
277 protected_header,
278 &plaintext,
279 cek,
280 ))
281 }
282 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead => {
283 let cek: &<Aes256CbcHmacSha256Aead as Aead>::Key =
284 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
285 Ok(Aes256CbcHmacSha256Aead::encrypt_cose0(
286 builder,
287 protected_header,
288 &plaintext,
289 cek,
290 ))
291 }
292 }
293}
294
295pub(crate) fn decrypt_cose0(
301 cose_encrypt0: &CoseEncrypt0,
302 policy: CoseAlgorithmPolicy,
303 cek: &[u8],
304) -> Result<Vec<u8>, CryptoError> {
305 let decrypted = match algorithm_from_header(&cose_encrypt0.protected.header, policy)? {
306 CoseContentEncryptionAlgorithm::Aes256Gcm => {
307 let cek: &<Aes256Gcm as Aead>::Key =
308 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
309 Aes256Gcm::decrypt_cose0(cose_encrypt0, cek)?
310 }
311 CoseContentEncryptionAlgorithm::XAes256Gcm => {
312 let cek: &<XAes256Gcm as Aead>::Key =
313 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
314 XAes256Gcm::decrypt_cose0(cose_encrypt0, cek)?
315 }
316 CoseContentEncryptionAlgorithm::XChaCha20Poly1305 => {
317 let cek: &<XChaCha20Poly1305 as Aead>::Key =
318 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
319 XChaCha20Poly1305::decrypt_cose0(cose_encrypt0, cek)?
320 }
321 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead => {
322 let cek: &<Aes256CbcHmacSha256Aead as Aead>::Key =
323 cek.try_into().map_err(|_| CryptoError::InvalidKeyLen)?;
324 Aes256CbcHmacSha256Aead::decrypt_cose0(cose_encrypt0, cek)?
325 }
326 };
327 if let Ok(content_format) = ContentFormat::try_from(&cose_encrypt0.protected.header)
328 && should_pad_content(&content_format)
329 {
330 return Ok(crate::keys::utils::unpad_bytes(&decrypted)?.to_vec());
331 }
332 Ok(decrypted)
333}
334
335pub(crate) trait CoseEncryptCipher: Aead {
338 const COSE_ALGORITHM: Algorithm;
341
342 fn encrypt_cose(
350 builder: CoseEncryptBuilder,
351 protected_header: Header,
352 plaintext: &[u8],
353 cek: &Self::Key,
354 ) -> CoseEncrypt;
355
356 fn decrypt_cose(cose_encrypt: &CoseEncrypt, cek: &Self::Key) -> Result<Vec<u8>, CryptoError>;
364
365 fn encrypt_cose0(
368 builder: CoseEncrypt0Builder,
369 protected_header: Header,
370 plaintext: &[u8],
371 cek: &Self::Key,
372 ) -> CoseEncrypt0;
373
374 fn decrypt_cose0(cose_encrypt0: &CoseEncrypt0, cek: &Self::Key)
377 -> Result<Vec<u8>, CryptoError>;
378}
379
380impl CoseEncryptCipher for Aes256Gcm {
381 const COSE_ALGORITHM: Algorithm = Algorithm::Assigned(iana::Algorithm::A256GCM);
382
383 fn encrypt_cose(
384 builder: CoseEncryptBuilder,
385 mut protected_header: Header,
386 plaintext: &[u8],
387 cek: &Self::Key,
388 ) -> CoseEncrypt {
389 protected_header.alg = Some(Self::COSE_ALGORITHM);
392
393 let nonce = Aes256GcmNonce::make();
397 builder
398 .protected(protected_header)
399 .unprotected(HeaderBuilder::new().iv(nonce.as_bytes().to_vec()).build())
400 .create_ciphertext(plaintext, &[], |data, aad| {
401 Aes256Gcm::encrypt(cek, &nonce, data, aad)
402 .encrypted_bytes()
403 .to_vec()
404 })
405 .build()
406 }
407
408 fn decrypt_cose(cose_encrypt: &CoseEncrypt, cek: &Self::Key) -> Result<Vec<u8>, CryptoError> {
409 ensure_algorithm_matches::<Self>(&cose_encrypt.protected.header)?;
413
414 let nonce = Aes256GcmNonce::try_from(cose_encrypt)?;
415 cose_encrypt.decrypt_ciphertext(
416 &[],
417 || CryptoError::MissingField("ciphertext"),
418 |data, aad| {
419 Aes256Gcm::decrypt(cek, &nonce, &Aes256GcmCiphertext::from(data.to_vec()), aad)
420 },
421 )
422 }
423
424 fn encrypt_cose0(
425 builder: CoseEncrypt0Builder,
426 mut protected_header: Header,
427 plaintext: &[u8],
428 cek: &Self::Key,
429 ) -> CoseEncrypt0 {
430 protected_header.alg = Some(Self::COSE_ALGORITHM);
431
432 let nonce = Aes256GcmNonce::make();
433 builder
434 .protected(protected_header)
435 .unprotected(HeaderBuilder::new().iv(nonce.as_bytes().to_vec()).build())
436 .create_ciphertext(plaintext, &[], |data, aad| {
437 Aes256Gcm::encrypt(cek, &nonce, data, aad)
438 .encrypted_bytes()
439 .to_vec()
440 })
441 .build()
442 }
443
444 fn decrypt_cose0(
445 cose_encrypt0: &CoseEncrypt0,
446 cek: &Self::Key,
447 ) -> Result<Vec<u8>, CryptoError> {
448 ensure_algorithm_matches::<Self>(&cose_encrypt0.protected.header)?;
449
450 let nonce = Aes256GcmNonce::try_from(cose_encrypt0)?;
451 cose_encrypt0.decrypt_ciphertext(
452 &[],
453 || CryptoError::MissingField("ciphertext"),
454 |data, aad| {
455 Aes256Gcm::decrypt(cek, &nonce, &Aes256GcmCiphertext::from(data.to_vec()), aad)
456 },
457 )
458 }
459}
460
461impl CoseEncryptCipher for XAes256Gcm {
462 const COSE_ALGORITHM: Algorithm = Algorithm::PrivateUse(XAES_256_GCM);
463
464 fn encrypt_cose(
465 builder: CoseEncryptBuilder,
466 mut protected_header: Header,
467 plaintext: &[u8],
468 cek: &Self::Key,
469 ) -> CoseEncrypt {
470 protected_header.alg = Some(Self::COSE_ALGORITHM);
471
472 let nonce = XAes256GcmNonce::make();
473 builder
474 .protected(protected_header)
475 .unprotected(HeaderBuilder::new().iv(nonce.as_bytes().to_vec()).build())
476 .create_ciphertext(plaintext, &[], |data, aad| {
477 XAes256Gcm::encrypt(cek, &nonce, data, aad)
478 .encrypted_bytes()
479 .to_vec()
480 })
481 .build()
482 }
483
484 fn decrypt_cose(cose_encrypt: &CoseEncrypt, cek: &Self::Key) -> Result<Vec<u8>, CryptoError> {
485 ensure_algorithm_matches::<Self>(&cose_encrypt.protected.header)?;
486
487 let nonce = XAes256GcmNonce::try_from(cose_encrypt)?;
488 cose_encrypt.decrypt_ciphertext(
489 &[],
490 || CryptoError::MissingField("ciphertext"),
491 |data, aad| {
492 XAes256Gcm::decrypt(cek, &nonce, &XAes256GcmCiphertext::from(data.to_vec()), aad)
493 },
494 )
495 }
496
497 fn encrypt_cose0(
498 builder: CoseEncrypt0Builder,
499 mut protected_header: Header,
500 plaintext: &[u8],
501 cek: &Self::Key,
502 ) -> CoseEncrypt0 {
503 protected_header.alg = Some(Self::COSE_ALGORITHM);
504
505 let nonce = XAes256GcmNonce::make();
506 builder
507 .protected(protected_header)
508 .unprotected(HeaderBuilder::new().iv(nonce.as_bytes().to_vec()).build())
509 .create_ciphertext(plaintext, &[], |data, aad| {
510 XAes256Gcm::encrypt(cek, &nonce, data, aad)
511 .encrypted_bytes()
512 .to_vec()
513 })
514 .build()
515 }
516
517 fn decrypt_cose0(
518 cose_encrypt0: &CoseEncrypt0,
519 cek: &Self::Key,
520 ) -> Result<Vec<u8>, CryptoError> {
521 ensure_algorithm_matches::<Self>(&cose_encrypt0.protected.header)?;
522
523 let nonce = XAes256GcmNonce::try_from(cose_encrypt0)?;
524 cose_encrypt0.decrypt_ciphertext(
525 &[],
526 || CryptoError::MissingField("ciphertext"),
527 |data, aad| {
528 XAes256Gcm::decrypt(cek, &nonce, &XAes256GcmCiphertext::from(data.to_vec()), aad)
529 },
530 )
531 }
532}
533
534impl CoseEncryptCipher for XChaCha20Poly1305 {
535 const COSE_ALGORITHM: Algorithm = Algorithm::PrivateUse(XCHACHA20_POLY1305);
536
537 fn encrypt_cose(
538 builder: CoseEncryptBuilder,
539 mut protected_header: Header,
540 plaintext: &[u8],
541 cek: &Self::Key,
542 ) -> CoseEncrypt {
543 protected_header.alg = Some(Self::COSE_ALGORITHM);
544
545 let nonce = XChaCha20Poly1305Nonce::make();
546 builder
547 .protected(protected_header)
548 .unprotected(HeaderBuilder::new().iv(nonce.as_bytes().to_vec()).build())
549 .create_ciphertext(plaintext, &[], |data, aad| {
550 XChaCha20Poly1305::encrypt(cek, &nonce, data, aad)
551 .encrypted_bytes()
552 .to_vec()
553 })
554 .build()
555 }
556
557 fn decrypt_cose(cose_encrypt: &CoseEncrypt, cek: &Self::Key) -> Result<Vec<u8>, CryptoError> {
558 ensure_algorithm_matches::<Self>(&cose_encrypt.protected.header)?;
559
560 let nonce = XChaCha20Poly1305Nonce::try_from(cose_encrypt)?;
561 cose_encrypt.decrypt_ciphertext(
562 &[],
563 || CryptoError::MissingField("ciphertext"),
564 |data, aad| {
565 XChaCha20Poly1305::decrypt(
566 cek,
567 &nonce,
568 &XChaCha20Poly1305Ciphertext::from(data.to_vec()),
569 aad,
570 )
571 },
572 )
573 }
574
575 fn encrypt_cose0(
576 builder: CoseEncrypt0Builder,
577 mut protected_header: Header,
578 plaintext: &[u8],
579 cek: &Self::Key,
580 ) -> CoseEncrypt0 {
581 protected_header.alg = Some(Self::COSE_ALGORITHM);
582
583 let nonce = XChaCha20Poly1305Nonce::make();
584 builder
585 .protected(protected_header)
586 .unprotected(HeaderBuilder::new().iv(nonce.as_bytes().to_vec()).build())
587 .create_ciphertext(plaintext, &[], |data, aad| {
588 XChaCha20Poly1305::encrypt(cek, &nonce, data, aad)
589 .encrypted_bytes()
590 .to_vec()
591 })
592 .build()
593 }
594
595 fn decrypt_cose0(
596 cose_encrypt0: &CoseEncrypt0,
597 cek: &Self::Key,
598 ) -> Result<Vec<u8>, CryptoError> {
599 ensure_algorithm_matches::<Self>(&cose_encrypt0.protected.header)?;
600
601 let nonce = XChaCha20Poly1305Nonce::try_from(cose_encrypt0)?;
602 cose_encrypt0.decrypt_ciphertext(
603 &[],
604 || CryptoError::MissingField("ciphertext"),
605 |data, aad| {
606 XChaCha20Poly1305::decrypt(
607 cek,
608 &nonce,
609 &XChaCha20Poly1305Ciphertext::from(data.to_vec()),
610 aad,
611 )
612 },
613 )
614 }
615}
616
617impl CoseEncryptCipher for Aes256CbcHmacSha256Aead {
618 const COSE_ALGORITHM: Algorithm = Algorithm::PrivateUse(AES_256_CBC_HMAC_SHA256_AEAD);
619
620 fn encrypt_cose(
621 builder: CoseEncryptBuilder,
622 mut protected_header: Header,
623 plaintext: &[u8],
624 cek: &Self::Key,
625 ) -> CoseEncrypt {
626 protected_header.alg = Some(Self::COSE_ALGORITHM);
627
628 let nonce = Aes256CbcHmacSha256AeadNonce::make();
629 builder
630 .protected(protected_header)
631 .unprotected(HeaderBuilder::new().iv(nonce.as_bytes().to_vec()).build())
632 .create_ciphertext(plaintext, &[], |data, aad| {
633 Aes256CbcHmacSha256Aead::encrypt(cek, &nonce, data, aad)
634 .encrypted_bytes()
635 .to_vec()
636 })
637 .build()
638 }
639
640 fn decrypt_cose(cose_encrypt: &CoseEncrypt, cek: &Self::Key) -> Result<Vec<u8>, CryptoError> {
641 ensure_algorithm_matches::<Self>(&cose_encrypt.protected.header)?;
642
643 let nonce = Aes256CbcHmacSha256AeadNonce::try_from(cose_encrypt)?;
644 cose_encrypt.decrypt_ciphertext(
645 &[],
646 || CryptoError::MissingField("ciphertext"),
647 |data, aad| {
648 Aes256CbcHmacSha256Aead::decrypt(
649 cek,
650 &nonce,
651 &Aes256CbcHmacSha256AeadCiphertext::from(data.to_vec()),
652 aad,
653 )
654 },
655 )
656 }
657
658 fn encrypt_cose0(
659 builder: CoseEncrypt0Builder,
660 mut protected_header: Header,
661 plaintext: &[u8],
662 cek: &Self::Key,
663 ) -> CoseEncrypt0 {
664 protected_header.alg = Some(Self::COSE_ALGORITHM);
665
666 let nonce = Aes256CbcHmacSha256AeadNonce::make();
667 builder
668 .protected(protected_header)
669 .unprotected(HeaderBuilder::new().iv(nonce.as_bytes().to_vec()).build())
670 .create_ciphertext(plaintext, &[], |data, aad| {
671 Aes256CbcHmacSha256Aead::encrypt(cek, &nonce, data, aad)
672 .encrypted_bytes()
673 .to_vec()
674 })
675 .build()
676 }
677
678 fn decrypt_cose0(
679 cose_encrypt0: &CoseEncrypt0,
680 cek: &Self::Key,
681 ) -> Result<Vec<u8>, CryptoError> {
682 ensure_algorithm_matches::<Self>(&cose_encrypt0.protected.header)?;
683
684 let nonce = Aes256CbcHmacSha256AeadNonce::try_from(cose_encrypt0)?;
685 cose_encrypt0.decrypt_ciphertext(
686 &[],
687 || CryptoError::MissingField("ciphertext"),
688 |data, aad| {
689 Aes256CbcHmacSha256Aead::decrypt(
690 cek,
691 &nonce,
692 &Aes256CbcHmacSha256AeadCiphertext::from(data.to_vec()),
693 aad,
694 )
695 },
696 )
697 }
698}
699
700pub(crate) fn encrypt_xchacha20_poly1305(
702 plaintext: &[u8],
703 key: &XChaCha20Poly1305Key,
704 content_format: ContentFormat,
705) -> Result<CoseEncrypt0Bytes, CryptoError> {
706 let mut plaintext = plaintext.to_vec();
707
708 let header_builder: coset::HeaderBuilder = content_format.into();
709 let mut protected_header = header_builder
710 .key_id(key.key_id.as_slice().to_vec())
711 .build();
712 protected_header.alg = Some(coset::Algorithm::PrivateUse(XCHACHA20_POLY1305));
716
717 if should_pad_content(&content_format) {
718 let min_length = TEXT_PAD_BLOCK_SIZE * (1 + (plaintext.len() / TEXT_PAD_BLOCK_SIZE));
719 crate::keys::utils::pad_bytes(&mut plaintext, min_length)?;
720 }
721
722 let nonce = XChaCha20Poly1305Nonce::make();
723 let cose_encrypt0 = coset::CoseEncrypt0Builder::new()
724 .protected(protected_header)
725 .create_ciphertext(&plaintext, &[], |data, aad| {
726 XChaCha20Poly1305::encrypt(&(*key.enc_key).into(), &nonce, data, aad)
727 .encrypted_bytes()
728 .to_vec()
729 })
730 .unprotected(
731 coset::HeaderBuilder::new()
732 .iv(nonce.as_bytes().to_vec())
733 .build(),
734 )
735 .build();
736
737 cose_encrypt0
738 .to_vec()
739 .map_err(|err| CryptoError::EncString(EncStringParseError::InvalidCoseEncoding(err)))
740 .map(CoseEncrypt0Bytes::from)
741}
742
743pub(crate) fn decrypt_xchacha20_poly1305(
745 cose_encrypt0_message: &CoseEncrypt0Bytes,
746 key: &XChaCha20Poly1305Key,
747) -> Result<(Vec<u8>, ContentFormat), CryptoError> {
748 let msg = coset::CoseEncrypt0::from_slice(cose_encrypt0_message.as_ref())
749 .map_err(|err| CryptoError::EncString(EncStringParseError::InvalidCoseEncoding(err)))?;
750
751 let Some(ref alg) = msg.protected.header.alg else {
752 return Err(CryptoError::EncString(
753 EncStringParseError::CoseMissingAlgorithm,
754 ));
755 };
756
757 if *alg != coset::Algorithm::PrivateUse(XCHACHA20_POLY1305) {
758 return Err(CryptoError::WrongKeyType);
759 }
760
761 let content_format = ContentFormat::try_from(&msg.protected.header)
762 .map_err(|_| CryptoError::EncString(EncStringParseError::CoseMissingContentType))?;
763
764 if key.key_id.as_slice() != msg.protected.header.key_id {
765 return Err(CryptoError::WrongCoseKeyId);
766 }
767
768 let nonce = XChaCha20Poly1305Nonce::try_from(&msg)?;
769 let decrypted_message = msg.decrypt_ciphertext(
770 &[],
771 || CryptoError::MissingField("ciphertext"),
772 |data, aad| {
773 XChaCha20Poly1305::decrypt(
774 &(*key.enc_key).into(),
775 &nonce,
776 &XChaCha20Poly1305Ciphertext::from(data.to_vec()),
777 aad,
778 )
779 },
780 )?;
781
782 if should_pad_content(&content_format) {
783 let data = crate::keys::utils::unpad_bytes(&decrypted_message)?;
784 return Ok((data.to_vec(), content_format));
785 }
786
787 Ok((decrypted_message, content_format))
788}
789
790pub(crate) fn encrypt_xaes256_gcm(
792 plaintext: &[u8],
793 key: &XAes256GcmKey,
794 content_format: ContentFormat,
795) -> Result<CoseEncrypt0Bytes, CryptoError> {
796 let mut plaintext = plaintext.to_vec();
797 let mut protected_header: Header = HeaderBuilder::from(content_format)
798 .key_id(key.key_id.as_slice().to_vec())
799 .build();
800 protected_header.alg = Some(Algorithm::PrivateUse(XAES_256_GCM));
801
802 if should_pad_content(&content_format) {
805 let min_length = TEXT_PAD_BLOCK_SIZE * (1 + (plaintext.len() / TEXT_PAD_BLOCK_SIZE));
806 crate::keys::utils::pad_bytes(&mut plaintext, min_length)?;
807 }
808
809 let nonce = XAes256GcmNonce::make();
810 CoseEncrypt0Builder::new()
811 .protected(protected_header)
812 .unprotected(HeaderBuilder::new().iv(nonce.as_bytes().to_vec()).build())
813 .create_ciphertext(&plaintext, &[], |data, aad| {
814 XAes256Gcm::encrypt(&(*key.enc_key).into(), &nonce, data, aad)
815 .encrypted_bytes()
816 .to_vec()
817 })
818 .build()
819 .to_vec()
820 .map_err(|err| CryptoError::EncString(EncStringParseError::InvalidCoseEncoding(err)))
821 .map(CoseEncrypt0Bytes::from)
822}
823
824pub(crate) fn decrypt_xaes256_gcm(
826 message: &CoseEncrypt0Bytes,
827 key: &XAes256GcmKey,
828) -> Result<(Vec<u8>, ContentFormat), CryptoError> {
829 let msg = CoseEncrypt0::from_slice(message.as_ref())
830 .map_err(|err| CryptoError::EncString(EncStringParseError::InvalidCoseEncoding(err)))?;
831
832 let Some(ref algorithm) = msg.protected.header.alg else {
833 return Err(CryptoError::EncString(
834 EncStringParseError::CoseMissingAlgorithm,
835 ));
836 };
837 if *algorithm != Algorithm::PrivateUse(XAES_256_GCM) {
838 return Err(CryptoError::WrongKeyType);
839 }
840
841 let content_format = ContentFormat::try_from(&msg.protected.header)
842 .map_err(|_| CryptoError::EncString(EncStringParseError::CoseMissingContentType))?;
843 if key.key_id.as_slice() != msg.protected.header.key_id {
844 return Err(CryptoError::WrongCoseKeyId);
845 }
846
847 let nonce = XAes256GcmNonce::try_from(&msg)?;
848 let decrypted = msg.decrypt_ciphertext(
849 &[],
850 || CryptoError::MissingField("ciphertext"),
851 |data, aad| {
852 XAes256Gcm::decrypt(
853 &(*key.enc_key).into(),
854 &nonce,
855 &XAes256GcmCiphertext::from(data.to_vec()),
856 aad,
857 )
858 },
859 )?;
860
861 if should_pad_content(&content_format) {
862 return Ok((
863 crate::keys::utils::unpad_bytes(&decrypted)?.to_vec(),
864 content_format,
865 ));
866 }
867
868 Ok((decrypted, content_format))
869}
870
871pub(crate) fn decrypt_aes256_cbc_hmac_aead(
875 message: &CoseEncrypt0Bytes,
876 key: &Aes256CbcHmacKey,
877) -> Result<(Vec<u8>, ContentFormat), CryptoError> {
878 let msg = CoseEncrypt0::from_slice(message.as_ref())
879 .map_err(|err| CryptoError::EncString(EncStringParseError::InvalidCoseEncoding(err)))?;
880
881 let Some(ref algorithm) = msg.protected.header.alg else {
882 return Err(CryptoError::EncString(
883 EncStringParseError::CoseMissingAlgorithm,
884 ));
885 };
886 if *algorithm != Algorithm::PrivateUse(AES_256_CBC_HMAC_SHA256_AEAD) {
887 return Err(CryptoError::WrongKeyType);
888 }
889
890 let content_format = ContentFormat::try_from(&msg.protected.header)
891 .map_err(|_| CryptoError::EncString(EncStringParseError::CoseMissingContentType))?;
892 if key.key_id().as_slice() != msg.protected.header.key_id {
893 return Err(CryptoError::WrongCoseKeyId);
894 }
895
896 let nonce = Aes256CbcHmacSha256AeadNonce::try_from(&msg)?;
897 let decrypted = msg.decrypt_ciphertext(
898 &[],
899 || CryptoError::MissingField("ciphertext"),
900 |data, aad| {
901 Aes256CbcHmacSha256Aead::decrypt(
902 key.as_composite_key(),
903 &nonce,
904 &Aes256CbcHmacSha256AeadCiphertext::from(data.to_vec()),
905 aad,
906 )
907 },
908 )?;
909
910 if should_pad_content(&content_format) {
911 return Ok((
912 crate::keys::utils::unpad_bytes(&decrypted)?.to_vec(),
913 content_format,
914 ));
915 }
916
917 Ok((decrypted, content_format))
918}
919
920#[cfg(test)]
921mod tests {
922 use coset::{CoseEncrypt0Builder, CoseEncryptBuilder, CoseRecipientBuilder, HeaderBuilder};
923 use hybrid_array::Array;
924 use iana::KeyOperation;
925
926 use super::*;
927 use crate::keys::KeyId;
928
929 const CEK: [u8; 32] = [7u8; 32];
930 const CEK_64: [u8; 64] = [7u8; 64];
932 const PLAINTEXT: &[u8] = b"content-encryption test vector";
933
934 const KEY_ID: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
935 const KEY_DATA: [u8; 32] = [
936 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
937 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
938 0x1e, 0x1f,
939 ];
940 const TEST_VECTOR_PLAINTEXT: &[u8] = b"Message test vector";
941 const TEST_VECTOR_COSE_ENCRYPT0: &[u8] = &[
942 131, 88, 28, 163, 1, 58, 0, 1, 17, 111, 3, 24, 42, 4, 80, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
943 11, 12, 13, 14, 15, 161, 5, 88, 24, 78, 20, 28, 157, 180, 246, 131, 220, 82, 104, 72, 73,
944 75, 43, 69, 139, 216, 167, 145, 220, 67, 168, 144, 173, 88, 35, 127, 234, 194, 83, 189,
945 172, 65, 29, 156, 73, 98, 87, 231, 87, 129, 15, 235, 127, 125, 97, 211, 51, 212, 211, 2,
946 13, 36, 123, 53, 12, 31, 191, 40, 13, 175,
947 ];
948
949 const TEST_VECTOR_AES256_CBC_HMAC_COSE_ENCRYPT0: &[u8] = &[
950 131, 88, 28, 163, 1, 58, 0, 1, 17, 122, 3, 24, 42, 4, 80, 172, 78, 207, 251, 46, 8, 122,
951 89, 24, 13, 29, 209, 153, 80, 184, 233, 161, 5, 80, 55, 75, 115, 189, 172, 49, 197, 173,
952 86, 194, 208, 7, 37, 220, 26, 141, 88, 64, 126, 139, 170, 11, 45, 71, 157, 51, 11, 88, 143,
953 209, 55, 20, 233, 101, 18, 59, 6, 218, 67, 253, 125, 84, 62, 121, 185, 250, 218, 33, 162,
954 128, 77, 180, 157, 50, 13, 17, 9, 106, 214, 220, 241, 165, 121, 26, 202, 211, 185, 2, 17,
955 180, 133, 229, 38, 180, 249, 13, 113, 124, 67, 36, 112, 254,
956 ];
957
958 fn algorithms() -> [(CoseContentEncryptionAlgorithm, &'static [u8]); 4] {
961 [
962 (CoseContentEncryptionAlgorithm::Aes256Gcm, &CEK),
963 (CoseContentEncryptionAlgorithm::XAes256Gcm, &CEK),
964 (CoseContentEncryptionAlgorithm::XChaCha20Poly1305, &CEK),
965 (
966 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead,
967 &CEK_64,
968 ),
969 ]
970 }
971
972 fn make_xaes_key() -> XAes256GcmKey {
973 XAes256GcmKey {
974 key_id: KeyId::from(KEY_ID),
975 enc_key: Box::pin(Array::from(KEY_DATA)),
976 supported_operations: vec![
977 KeyOperation::Decrypt,
978 KeyOperation::Encrypt,
979 KeyOperation::WrapKey,
980 KeyOperation::UnwrapKey,
981 ],
982 }
983 }
984
985 fn make_xchacha_key() -> XChaCha20Poly1305Key {
986 XChaCha20Poly1305Key {
987 key_id: KeyId::from(KEY_ID),
988 enc_key: Box::pin(Array::from(KEY_DATA)),
989 supported_operations: vec![
990 KeyOperation::Decrypt,
991 KeyOperation::Encrypt,
992 KeyOperation::WrapKey,
993 KeyOperation::UnwrapKey,
994 ],
995 }
996 }
997
998 #[test]
999 fn test_encrypt_decrypt_cose_roundtrip() {
1000 for (algorithm, cek) in algorithms() {
1001 let builder =
1002 CoseEncryptBuilder::new().add_recipient(CoseRecipientBuilder::new().build());
1003 let cose_encrypt = encrypt_cose(
1004 algorithm,
1005 builder,
1006 HeaderBuilder::new().build(),
1007 PLAINTEXT,
1008 cek,
1009 )
1010 .unwrap();
1011 let decrypted =
1012 decrypt_cose(&cose_encrypt, CoseAlgorithmPolicy::Exactly(algorithm), cek).unwrap();
1013 assert_eq!(decrypted, PLAINTEXT);
1014 }
1015 }
1016
1017 #[test]
1018 fn test_encrypt_decrypt_cose0_roundtrip() {
1019 for (algorithm, cek) in algorithms() {
1020 let cose_encrypt0 = encrypt_cose0(
1021 algorithm,
1022 CoseEncrypt0Builder::new(),
1023 HeaderBuilder::new().build(),
1024 PLAINTEXT,
1025 cek,
1026 )
1027 .unwrap();
1028 let decrypted =
1029 decrypt_cose0(&cose_encrypt0, CoseAlgorithmPolicy::Exactly(algorithm), cek)
1030 .unwrap();
1031 assert_eq!(decrypted, PLAINTEXT);
1032 }
1033 }
1034
1035 #[test]
1038 fn test_aes256_cbc_hmac_rejects_wrong_length_cek() {
1039 assert!(matches!(
1040 encrypt_cose0(
1041 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead,
1042 CoseEncrypt0Builder::new(),
1043 HeaderBuilder::new().build(),
1044 PLAINTEXT,
1045 &CEK,
1046 ),
1047 Err(CryptoError::InvalidKeyLen)
1048 ));
1049 }
1050
1051 #[test]
1052 fn test_aes256_cbc_hmac_cose0_fails_with_wrong_key() {
1053 let message = encrypt_cose0(
1054 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead,
1055 CoseEncrypt0Builder::new(),
1056 HeaderBuilder::new().build(),
1057 PLAINTEXT,
1058 &CEK_64,
1059 )
1060 .unwrap();
1061
1062 let mut wrong_cek = CEK_64;
1063 wrong_cek[0] ^= 1;
1064 assert!(
1065 decrypt_cose0(
1066 &message,
1067 CoseAlgorithmPolicy::Exactly(
1068 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead
1069 ),
1070 &wrong_cek,
1071 )
1072 .is_err()
1073 );
1074
1075 let mut wrong_mac_key = CEK_64;
1077 wrong_mac_key[32] ^= 1;
1078 assert!(
1079 decrypt_cose0(
1080 &message,
1081 CoseAlgorithmPolicy::Exactly(
1082 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead
1083 ),
1084 &wrong_mac_key,
1085 )
1086 .is_err()
1087 );
1088 }
1089
1090 #[test]
1091 fn test_aes256_cbc_hmac_cose0_fails_when_ciphertext_tampered() {
1092 let mut message = encrypt_cose0(
1093 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead,
1094 CoseEncrypt0Builder::new(),
1095 HeaderBuilder::new().build(),
1096 PLAINTEXT,
1097 &CEK_64,
1098 )
1099 .unwrap();
1100
1101 message.ciphertext.as_mut().unwrap()[0] ^= 1;
1102 assert!(
1103 decrypt_cose0(
1104 &message,
1105 CoseAlgorithmPolicy::Exactly(
1106 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead
1107 ),
1108 &CEK_64,
1109 )
1110 .is_err()
1111 );
1112 }
1113
1114 #[test]
1117 fn test_aes256_cbc_hmac_cose0_rejects_mismatched_policy() {
1118 let message = encrypt_cose0(
1119 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead,
1120 CoseEncrypt0Builder::new(),
1121 HeaderBuilder::new().build(),
1122 PLAINTEXT,
1123 &CEK_64,
1124 )
1125 .unwrap();
1126
1127 assert_eq!(
1128 message.protected.header.alg,
1129 Some(Algorithm::PrivateUse(AES_256_CBC_HMAC_SHA256_AEAD))
1130 );
1131 assert!(matches!(
1132 decrypt_cose0(
1133 &message,
1134 CoseAlgorithmPolicy::Exactly(CoseContentEncryptionAlgorithm::Aes256Gcm),
1135 &CEK_64,
1136 ),
1137 Err(CryptoError::WrongKeyType)
1138 ));
1139 }
1140
1141 #[test]
1142 fn test_decrypt_cose_algorithm_policies() {
1143 let builder =
1144 || CoseEncryptBuilder::new().add_recipient(CoseRecipientBuilder::new().build());
1145 let message = encrypt_cose(
1146 CoseContentEncryptionAlgorithm::XChaCha20Poly1305,
1147 builder(),
1148 HeaderBuilder::new().build(),
1149 PLAINTEXT,
1150 &CEK,
1151 )
1152 .unwrap();
1153
1154 assert_eq!(
1155 decrypt_cose(
1156 &message,
1157 CoseAlgorithmPolicy::Exactly(CoseContentEncryptionAlgorithm::XChaCha20Poly1305,),
1158 &CEK,
1159 )
1160 .unwrap(),
1161 PLAINTEXT
1162 );
1163 assert!(matches!(
1164 decrypt_cose(
1165 &message,
1166 CoseAlgorithmPolicy::Exactly(CoseContentEncryptionAlgorithm::Aes256Gcm),
1167 &CEK,
1168 ),
1169 Err(CryptoError::WrongKeyType)
1170 ));
1171 assert_eq!(
1172 decrypt_cose(
1173 &message,
1174 CoseAlgorithmPolicy::ProtectedHeaderAlgorithmOrLegacyDefault(
1175 CoseContentEncryptionAlgorithm::Aes256Gcm,
1176 ),
1177 &CEK,
1178 )
1179 .unwrap(),
1180 PLAINTEXT
1181 );
1182
1183 let missing_algorithm = builder()
1184 .protected(HeaderBuilder::new().build())
1185 .create_ciphertext(PLAINTEXT, &[], |data, _| data.to_vec())
1186 .build();
1187 for policy in [
1188 CoseAlgorithmPolicy::RequireProtectedHeaderAlgorithm,
1189 CoseAlgorithmPolicy::Exactly(CoseContentEncryptionAlgorithm::XChaCha20Poly1305),
1190 ] {
1191 assert!(matches!(
1192 decrypt_cose(&missing_algorithm, policy, &CEK),
1193 Err(CryptoError::EncString(
1194 EncStringParseError::CoseMissingAlgorithm
1195 ))
1196 ));
1197 }
1198
1199 let nonce = XChaCha20Poly1305Nonce::make();
1200 let legacy_message = builder()
1201 .protected(HeaderBuilder::new().build())
1202 .unprotected(HeaderBuilder::new().iv(nonce.as_bytes().to_vec()).build())
1203 .create_ciphertext(PLAINTEXT, &[], |data, aad| {
1204 XChaCha20Poly1305::encrypt(&CEK, &nonce, data, aad)
1205 .encrypted_bytes()
1206 .to_vec()
1207 })
1208 .build();
1209 assert_eq!(
1210 decrypt_cose(
1211 &legacy_message,
1212 CoseAlgorithmPolicy::ProtectedHeaderAlgorithmOrLegacyDefault(
1213 CoseContentEncryptionAlgorithm::XChaCha20Poly1305,
1214 ),
1215 &CEK,
1216 )
1217 .unwrap(),
1218 PLAINTEXT
1219 );
1220 }
1221
1222 #[test]
1223 fn test_decrypt_cose0_algorithm_policies() {
1224 let message = encrypt_cose0(
1225 CoseContentEncryptionAlgorithm::XChaCha20Poly1305,
1226 CoseEncrypt0Builder::new(),
1227 HeaderBuilder::new().build(),
1228 PLAINTEXT,
1229 &CEK,
1230 )
1231 .unwrap();
1232
1233 assert_eq!(
1234 decrypt_cose0(
1235 &message,
1236 CoseAlgorithmPolicy::Exactly(CoseContentEncryptionAlgorithm::XChaCha20Poly1305,),
1237 &CEK,
1238 )
1239 .unwrap(),
1240 PLAINTEXT
1241 );
1242 assert!(matches!(
1243 decrypt_cose0(
1244 &message,
1245 CoseAlgorithmPolicy::Exactly(CoseContentEncryptionAlgorithm::Aes256Gcm),
1246 &CEK,
1247 ),
1248 Err(CryptoError::WrongKeyType)
1249 ));
1250 assert_eq!(
1251 decrypt_cose0(
1252 &message,
1253 CoseAlgorithmPolicy::ProtectedHeaderAlgorithmOrLegacyDefault(
1254 CoseContentEncryptionAlgorithm::Aes256Gcm,
1255 ),
1256 &CEK,
1257 )
1258 .unwrap(),
1259 PLAINTEXT
1260 );
1261
1262 let missing_algorithm = CoseEncrypt0Builder::new()
1263 .protected(HeaderBuilder::new().build())
1264 .create_ciphertext(PLAINTEXT, &[], |data, _| data.to_vec())
1265 .build();
1266 assert!(matches!(
1267 decrypt_cose0(
1268 &missing_algorithm,
1269 CoseAlgorithmPolicy::Exactly(CoseContentEncryptionAlgorithm::XChaCha20Poly1305),
1270 &CEK,
1271 ),
1272 Err(CryptoError::EncString(
1273 EncStringParseError::CoseMissingAlgorithm
1274 ))
1275 ));
1276 }
1277
1278 #[test]
1279 fn test_decrypt_cose0_wrong_key_fails() {
1280 let cose_encrypt0 = encrypt_cose0(
1281 CoseContentEncryptionAlgorithm::XChaCha20Poly1305,
1282 CoseEncrypt0Builder::new(),
1283 HeaderBuilder::new().build(),
1284 PLAINTEXT,
1285 &CEK,
1286 )
1287 .unwrap();
1288 let wrong_cek = [0u8; 32];
1289 assert!(
1290 decrypt_cose0(
1291 &cose_encrypt0,
1292 CoseAlgorithmPolicy::Exactly(CoseContentEncryptionAlgorithm::XChaCha20Poly1305),
1293 &wrong_cek
1294 )
1295 .is_err()
1296 );
1297 }
1298
1299 #[test]
1300 fn test_decrypt_xaes256_gcm_wrong_key_fails() {
1301 let cose_encrypt0 = encrypt_cose0(
1302 CoseContentEncryptionAlgorithm::XAes256Gcm,
1303 CoseEncrypt0Builder::new(),
1304 HeaderBuilder::new().build(),
1305 PLAINTEXT,
1306 &CEK,
1307 )
1308 .unwrap();
1309
1310 assert!(matches!(
1311 decrypt_cose0(
1312 &cose_encrypt0,
1313 CoseAlgorithmPolicy::Exactly(CoseContentEncryptionAlgorithm::XAes256Gcm),
1314 &[0u8; 32]
1315 ),
1316 Err(CryptoError::KeyDecrypt)
1317 ));
1318 }
1319
1320 #[test]
1321 fn test_xaes256_gcm_emits_24_byte_nonce() {
1322 let cose_encrypt = encrypt_cose(
1323 CoseContentEncryptionAlgorithm::XAes256Gcm,
1324 CoseEncryptBuilder::new().add_recipient(CoseRecipientBuilder::new().build()),
1325 HeaderBuilder::new().build(),
1326 PLAINTEXT,
1327 &CEK,
1328 )
1329 .unwrap();
1330 let cose_encrypt0 = encrypt_cose0(
1331 CoseContentEncryptionAlgorithm::XAes256Gcm,
1332 CoseEncrypt0Builder::new(),
1333 HeaderBuilder::new().build(),
1334 PLAINTEXT,
1335 &CEK,
1336 )
1337 .unwrap();
1338
1339 assert_eq!(cose_encrypt.unprotected.iv.len(), 24);
1340 assert_eq!(cose_encrypt0.unprotected.iv.len(), 24);
1341 }
1342
1343 #[test]
1344 fn test_decrypt_xaes256_gcm_wrong_nonce_fails() {
1345 let mut cose_encrypt0 = encrypt_cose0(
1346 CoseContentEncryptionAlgorithm::XAes256Gcm,
1347 CoseEncrypt0Builder::new(),
1348 HeaderBuilder::new().build(),
1349 PLAINTEXT,
1350 &CEK,
1351 )
1352 .unwrap();
1353 cose_encrypt0.unprotected.iv[0] ^= 1;
1354
1355 assert!(matches!(
1356 decrypt_cose0(
1357 &cose_encrypt0,
1358 CoseAlgorithmPolicy::Exactly(CoseContentEncryptionAlgorithm::XAes256Gcm),
1359 &CEK
1360 ),
1361 Err(CryptoError::KeyDecrypt)
1362 ));
1363 }
1364
1365 #[test]
1366 fn test_decrypt_xaes256_gcm_malformed_nonce_fails() {
1367 let mut cose_encrypt0 = encrypt_cose0(
1368 CoseContentEncryptionAlgorithm::XAes256Gcm,
1369 CoseEncrypt0Builder::new(),
1370 HeaderBuilder::new().build(),
1371 PLAINTEXT,
1372 &CEK,
1373 )
1374 .unwrap();
1375 cose_encrypt0.unprotected.iv.pop();
1376
1377 assert!(matches!(
1378 decrypt_cose0(
1379 &cose_encrypt0,
1380 CoseAlgorithmPolicy::Exactly(CoseContentEncryptionAlgorithm::XAes256Gcm),
1381 &CEK
1382 ),
1383 Err(CryptoError::InvalidNonceLength)
1384 ));
1385 }
1386
1387 #[test]
1388 fn test_decrypt_cose0_missing_algorithm_fails_without_default() {
1389 let cose_encrypt0 = CoseEncrypt0Builder::new()
1391 .protected(HeaderBuilder::new().build())
1392 .create_ciphertext(PLAINTEXT, &[], |data, _| data.to_vec())
1393 .build();
1394 assert!(matches!(
1395 decrypt_cose0(
1396 &cose_encrypt0,
1397 CoseAlgorithmPolicy::RequireProtectedHeaderAlgorithm,
1398 &CEK
1399 ),
1400 Err(CryptoError::EncString(
1401 EncStringParseError::CoseMissingAlgorithm
1402 ))
1403 ));
1404 }
1405
1406 #[test]
1407 fn test_decrypt_cose0_missing_algorithm_uses_default() {
1408 let nonce = XChaCha20Poly1305Nonce::make();
1412 let cose_encrypt0 = CoseEncrypt0Builder::new()
1413 .protected(HeaderBuilder::new().build())
1414 .unprotected(HeaderBuilder::new().iv(nonce.as_bytes().to_vec()).build())
1415 .create_ciphertext(PLAINTEXT, &[], |data, aad| {
1416 XChaCha20Poly1305::encrypt(&CEK, &nonce, data, aad)
1417 .encrypted_bytes()
1418 .to_vec()
1419 })
1420 .build();
1421
1422 let decrypted = decrypt_cose0(
1423 &cose_encrypt0,
1424 CoseAlgorithmPolicy::ProtectedHeaderAlgorithmOrLegacyDefault(
1425 CoseContentEncryptionAlgorithm::XChaCha20Poly1305,
1426 ),
1427 &CEK,
1428 )
1429 .unwrap();
1430 assert_eq!(decrypted, PLAINTEXT);
1431 }
1432
1433 #[test]
1434 fn test_encrypt_decrypt_xchacha20_roundtrip_octetstream() {
1435 use crate::SymmetricCryptoKey;
1436 let SymmetricCryptoKey::XChaCha20Poly1305Key(ref key) =
1437 SymmetricCryptoKey::make_xchacha20_poly1305_key()
1438 else {
1439 panic!("Failed to create XChaCha20Poly1305Key");
1440 };
1441
1442 let plaintext = b"Hello, world!";
1443 let encrypted =
1444 encrypt_xchacha20_poly1305(plaintext, key, ContentFormat::OctetStream).unwrap();
1445 let decrypted = decrypt_xchacha20_poly1305(&encrypted, key).unwrap();
1446 assert_eq!(decrypted, (plaintext.to_vec(), ContentFormat::OctetStream));
1447 }
1448
1449 #[test]
1450 fn test_encrypt_decrypt_xchacha20_roundtrip_utf8() {
1451 use crate::SymmetricCryptoKey;
1452 let SymmetricCryptoKey::XChaCha20Poly1305Key(ref key) =
1453 SymmetricCryptoKey::make_xchacha20_poly1305_key()
1454 else {
1455 panic!("Failed to create XChaCha20Poly1305Key");
1456 };
1457
1458 let plaintext = b"Hello, world!";
1459 let encrypted = encrypt_xchacha20_poly1305(plaintext, key, ContentFormat::Utf8).unwrap();
1460 let decrypted = decrypt_xchacha20_poly1305(&encrypted, key).unwrap();
1461 assert_eq!(decrypted, (plaintext.to_vec(), ContentFormat::Utf8));
1462 }
1463
1464 #[test]
1465 fn test_encrypt_decrypt_xchacha20_roundtrip_pkcs8() {
1466 use crate::SymmetricCryptoKey;
1467 let SymmetricCryptoKey::XChaCha20Poly1305Key(ref key) =
1468 SymmetricCryptoKey::make_xchacha20_poly1305_key()
1469 else {
1470 panic!("Failed to create XChaCha20Poly1305Key");
1471 };
1472
1473 let plaintext = b"Hello, world!";
1474 let encrypted =
1475 encrypt_xchacha20_poly1305(plaintext, key, ContentFormat::Pkcs8PrivateKey).unwrap();
1476 let decrypted = decrypt_xchacha20_poly1305(&encrypted, key).unwrap();
1477 assert_eq!(
1478 decrypted,
1479 (plaintext.to_vec(), ContentFormat::Pkcs8PrivateKey)
1480 );
1481 }
1482
1483 #[test]
1484 fn test_encrypt_decrypt_xchacha20_roundtrip_cosekey() {
1485 use crate::SymmetricCryptoKey;
1486 let SymmetricCryptoKey::XChaCha20Poly1305Key(ref key) =
1487 SymmetricCryptoKey::make_xchacha20_poly1305_key()
1488 else {
1489 panic!("Failed to create XChaCha20Poly1305Key");
1490 };
1491
1492 let plaintext = b"Hello, world!";
1493 let encrypted = encrypt_xchacha20_poly1305(plaintext, key, ContentFormat::CoseKey).unwrap();
1494 let decrypted = decrypt_xchacha20_poly1305(&encrypted, key).unwrap();
1495 assert_eq!(decrypted, (plaintext.to_vec(), ContentFormat::CoseKey));
1496 }
1497
1498 #[test]
1499 fn test_decrypt_xchacha20_test_vector() {
1500 let key = make_xchacha_key();
1501 let decrypted =
1502 decrypt_xchacha20_poly1305(&CoseEncrypt0Bytes::from(TEST_VECTOR_COSE_ENCRYPT0), &key)
1503 .unwrap();
1504 assert_eq!(
1505 decrypted,
1506 (TEST_VECTOR_PLAINTEXT.to_vec(), ContentFormat::OctetStream)
1507 );
1508 }
1509
1510 #[test]
1511 fn test_decrypt_xchacha20_fail_wrong_key_id() {
1512 let key = XChaCha20Poly1305Key {
1513 key_id: KeyId::from([1; 16]),
1514 enc_key: Box::pin(Array::from(KEY_DATA)),
1515 supported_operations: vec![
1516 KeyOperation::Decrypt,
1517 KeyOperation::Encrypt,
1518 KeyOperation::WrapKey,
1519 KeyOperation::UnwrapKey,
1520 ],
1521 };
1522 assert!(matches!(
1523 decrypt_xchacha20_poly1305(&CoseEncrypt0Bytes::from(TEST_VECTOR_COSE_ENCRYPT0), &key),
1524 Err(CryptoError::WrongCoseKeyId)
1525 ));
1526 }
1527
1528 #[test]
1529 fn test_decrypt_xchacha20_fail_wrong_algorithm() {
1530 use coset::iana;
1531 let protected_header = coset::HeaderBuilder::new()
1532 .algorithm(iana::Algorithm::A256GCM)
1533 .key_id(KEY_ID.to_vec())
1534 .build();
1535 let nonce = [0u8; 16];
1536 let cose_encrypt0 = coset::CoseEncrypt0Builder::new()
1537 .protected(protected_header)
1538 .create_ciphertext(&[], &[], |_, _| Vec::new())
1539 .unprotected(coset::HeaderBuilder::new().iv(nonce.to_vec()).build())
1540 .build();
1541 let serialized_message = CoseEncrypt0Bytes::from(cose_encrypt0.to_vec().unwrap());
1542
1543 let key = make_xchacha_key();
1544 assert!(matches!(
1545 decrypt_xchacha20_poly1305(&serialized_message, &key),
1546 Err(CryptoError::WrongKeyType)
1547 ));
1548 }
1549
1550 fn make_aes_cbc_hmac_key() -> Aes256CbcHmacKey {
1552 Aes256CbcHmacKey::new(
1553 &std::array::from_fn(|i| i as u8),
1554 &std::array::from_fn(|i| (i + 32) as u8),
1555 )
1556 }
1557
1558 fn encrypt_aes256_cbc_hmac(
1560 plaintext: &[u8],
1561 key: &Aes256CbcHmacKey,
1562 content_format: ContentFormat,
1563 ) -> CoseEncrypt0Bytes {
1564 let protected_header = HeaderBuilder::from(content_format)
1565 .key_id(key.key_id().as_slice().to_vec())
1566 .build();
1567 encrypt_cose0(
1568 CoseContentEncryptionAlgorithm::Aes256CbcHmacSha256Aead,
1569 CoseEncrypt0Builder::new(),
1570 protected_header,
1571 plaintext,
1572 key.as_composite_key(),
1573 )
1574 .unwrap()
1575 .to_vec()
1576 .unwrap()
1577 .into()
1578 }
1579
1580 #[test]
1581 #[ignore = "Generates test vectors; run manually"]
1582 fn generate_aes256_cbc_hmac_test_vector() {
1583 let encrypted = encrypt_aes256_cbc_hmac(
1584 TEST_VECTOR_PLAINTEXT,
1585 &make_aes_cbc_hmac_key(),
1586 ContentFormat::OctetStream,
1587 );
1588 println!(
1589 "const TEST_VECTOR_AES256_CBC_HMAC_COSE_ENCRYPT0: &[u8] = &{:?};",
1590 encrypted.as_ref()
1591 );
1592 }
1593
1594 #[test]
1597 fn test_decrypt_aes256_cbc_hmac_test_vector() {
1598 let decrypted = decrypt_aes256_cbc_hmac_aead(
1599 &CoseEncrypt0Bytes::from(TEST_VECTOR_AES256_CBC_HMAC_COSE_ENCRYPT0),
1600 &make_aes_cbc_hmac_key(),
1601 )
1602 .unwrap();
1603 assert_eq!(
1604 decrypted,
1605 (TEST_VECTOR_PLAINTEXT.to_vec(), ContentFormat::OctetStream)
1606 );
1607 }
1608
1609 #[test]
1610 fn test_decrypt_aes256_cbc_hmac_content_formats() {
1611 let key = make_aes_cbc_hmac_key();
1612 for content_format in [
1613 ContentFormat::OctetStream,
1614 ContentFormat::Utf8,
1615 ContentFormat::Pkcs8PrivateKey,
1616 ContentFormat::CoseKey,
1617 ] {
1618 let encrypted = encrypt_aes256_cbc_hmac(TEST_VECTOR_PLAINTEXT, &key, content_format);
1619 assert_eq!(
1620 decrypt_aes256_cbc_hmac_aead(&encrypted, &key).unwrap(),
1621 (TEST_VECTOR_PLAINTEXT.to_vec(), content_format)
1622 );
1623 }
1624 }
1625
1626 #[test]
1627 fn test_decrypt_aes256_cbc_hmac_fail_wrong_key_id() {
1628 let other_key = Aes256CbcHmacKey::new(&[1u8; 32], &[2u8; 32]);
1629 assert!(matches!(
1630 decrypt_aes256_cbc_hmac_aead(
1631 &CoseEncrypt0Bytes::from(TEST_VECTOR_AES256_CBC_HMAC_COSE_ENCRYPT0),
1632 &other_key
1633 ),
1634 Err(CryptoError::WrongCoseKeyId)
1635 ));
1636 }
1637
1638 #[test]
1639 fn test_decrypt_aes256_cbc_hmac_fail_wrong_algorithm() {
1640 assert!(matches!(
1642 decrypt_aes256_cbc_hmac_aead(
1643 &CoseEncrypt0Bytes::from(TEST_VECTOR_COSE_ENCRYPT0),
1644 &make_aes_cbc_hmac_key()
1645 ),
1646 Err(CryptoError::WrongKeyType)
1647 ));
1648 }
1649
1650 #[test]
1651 fn test_decrypt_aes256_cbc_hmac_fail_tampered_ciphertext() {
1652 let message = CoseEncrypt0::from_slice(TEST_VECTOR_AES256_CBC_HMAC_COSE_ENCRYPT0).unwrap();
1653 let mut ciphertext = message.ciphertext.clone().unwrap();
1654 ciphertext[0] ^= 1;
1655 let tampered: CoseEncrypt0Bytes = CoseEncrypt0Builder::new()
1656 .protected(message.protected.header)
1657 .unprotected(message.unprotected)
1658 .ciphertext(ciphertext)
1659 .build()
1660 .to_vec()
1661 .unwrap()
1662 .into();
1663
1664 assert!(matches!(
1665 decrypt_aes256_cbc_hmac_aead(&tampered, &make_aes_cbc_hmac_key()),
1666 Err(CryptoError::KeyDecrypt)
1667 ));
1668 }
1669
1670 fn xaes_message(content_format: ContentFormat) -> CoseEncrypt0 {
1671 let encoded =
1672 encrypt_xaes256_gcm(TEST_VECTOR_PLAINTEXT, &make_xaes_key(), content_format).unwrap();
1673 CoseEncrypt0::from_slice(encoded.as_ref()).unwrap()
1674 }
1675
1676 fn rebuild_xaes_message(message: CoseEncrypt0, protected: Header) -> CoseEncrypt0Bytes {
1677 CoseEncrypt0Builder::new()
1678 .protected(protected)
1679 .unprotected(message.unprotected)
1680 .ciphertext(message.ciphertext.unwrap())
1681 .build()
1682 .to_vec()
1683 .unwrap()
1684 .into()
1685 }
1686
1687 #[test]
1688 fn test_xaes256_gcm_roundtrip_content_formats() {
1689 for content_format in [
1690 ContentFormat::OctetStream,
1691 ContentFormat::Utf8,
1692 ContentFormat::Pkcs8PrivateKey,
1693 ContentFormat::CoseKey,
1694 ] {
1695 let encrypted =
1696 encrypt_xaes256_gcm(TEST_VECTOR_PLAINTEXT, &make_xaes_key(), content_format)
1697 .unwrap();
1698 assert_eq!(
1699 decrypt_xaes256_gcm(&encrypted, &make_xaes_key()).unwrap(),
1700 (TEST_VECTOR_PLAINTEXT.to_vec(), content_format)
1701 );
1702 }
1703 }
1704
1705 #[test]
1706 fn test_xaes256_gcm_key_id_and_authentication_failures() {
1707 let encrypted = encrypt_xaes256_gcm(
1708 TEST_VECTOR_PLAINTEXT,
1709 &make_xaes_key(),
1710 ContentFormat::OctetStream,
1711 )
1712 .unwrap();
1713
1714 let mut wrong_bytes = make_xaes_key();
1715 wrong_bytes.enc_key[0] ^= 1;
1716 assert!(matches!(
1717 decrypt_xaes256_gcm(&encrypted, &wrong_bytes),
1718 Err(CryptoError::KeyDecrypt)
1719 ));
1720
1721 let mut wrong_id = make_xaes_key();
1722 wrong_id.key_id = KeyId::from([1; 16]);
1723 assert!(matches!(
1724 decrypt_xaes256_gcm(&encrypted, &wrong_id),
1725 Err(CryptoError::WrongCoseKeyId)
1726 ));
1727 }
1728
1729 #[test]
1730 fn test_xaes256_gcm_rejects_invalid_protected_headers() {
1731 let key = make_xaes_key();
1732
1733 let mut message = xaes_message(ContentFormat::OctetStream);
1734 message.protected.header.alg = Some(Algorithm::Assigned(iana::Algorithm::A256GCM));
1735 let encrypted = rebuild_xaes_message(message.clone(), message.protected.header.clone());
1736 assert!(matches!(
1737 decrypt_xaes256_gcm(&encrypted, &key),
1738 Err(CryptoError::WrongKeyType)
1739 ));
1740
1741 message.protected.header.alg = None;
1742 let encrypted = rebuild_xaes_message(message.clone(), message.protected.header.clone());
1743 assert!(matches!(
1744 decrypt_xaes256_gcm(&encrypted, &key),
1745 Err(CryptoError::EncString(
1746 EncStringParseError::CoseMissingAlgorithm
1747 ))
1748 ));
1749
1750 for content_type in [
1751 None,
1752 Some(coset::ContentType::Text("application/unsupported".into())),
1753 ] {
1754 message.protected.header.alg = Some(Algorithm::PrivateUse(XAES_256_GCM));
1755 message.protected.header.content_type = content_type;
1756 let encrypted = rebuild_xaes_message(message.clone(), message.protected.header.clone());
1757 assert!(matches!(
1758 decrypt_xaes256_gcm(&encrypted, &key),
1759 Err(CryptoError::EncString(
1760 EncStringParseError::CoseMissingContentType
1761 ))
1762 ));
1763 }
1764 }
1765
1766 #[test]
1767 fn test_xaes256_gcm_rejects_missing_or_malformed_fields() {
1768 let key = make_xaes_key();
1769 let mut message = xaes_message(ContentFormat::OctetStream);
1770 message.ciphertext = None;
1771 let encrypted = message.to_vec().unwrap().into();
1772 assert!(matches!(
1773 decrypt_xaes256_gcm(&encrypted, &key),
1774 Err(CryptoError::MissingField("ciphertext"))
1775 ));
1776
1777 let mut message = xaes_message(ContentFormat::OctetStream);
1778 message.unprotected.iv.pop();
1779 let encrypted = message.to_vec().unwrap().into();
1780 assert!(matches!(
1781 decrypt_xaes256_gcm(&encrypted, &key),
1782 Err(CryptoError::InvalidNonceLength)
1783 ));
1784
1785 assert!(matches!(
1786 decrypt_xaes256_gcm(&CoseEncrypt0Bytes::from([0xff].as_slice()), &key),
1787 Err(CryptoError::EncString(
1788 EncStringParseError::InvalidCoseEncoding(_)
1789 ))
1790 ));
1791 }
1792
1793 #[test]
1794 fn test_xaes256_gcm_rejects_invalid_padding() {
1795 let key = make_xaes_key();
1796 let nonce = XAes256GcmNonce::make();
1797 let mut protected = HeaderBuilder::from(ContentFormat::Utf8)
1798 .key_id(KEY_ID.to_vec())
1799 .build();
1800 protected.alg = Some(Algorithm::PrivateUse(XAES_256_GCM));
1801 let message = CoseEncrypt0Builder::new()
1802 .protected(protected)
1803 .unprotected(HeaderBuilder::new().iv(nonce.as_bytes().to_vec()).build())
1804 .create_ciphertext(&[0], &[], |data, aad| {
1805 XAes256Gcm::encrypt(&KEY_DATA, &nonce, data, aad)
1806 .encrypted_bytes()
1807 .to_vec()
1808 })
1809 .build()
1810 .to_vec()
1811 .unwrap()
1812 .into();
1813
1814 assert!(matches!(
1815 decrypt_xaes256_gcm(&message, &key),
1816 Err(CryptoError::InvalidPadding)
1817 ));
1818 }
1819}