1use chacha20poly1305::{ChaCha20Poly1305, KeyInit, aead::AeadInOut};
7use hkdf::Hkdf;
8use hmac::{Hmac, Mac};
9use hpke::{
10 Deserializable, Kem, OpModeR, OpModeS, Serializable,
11 aead::{AeadTag, ChaCha20Poly1305 as HpkeAead},
12 kdf::HkdfSha256,
13 kem::XWing,
14};
15use rand::{CryptoRng, SeedableRng, rngs::StdRng};
16use sha2::{Digest, Sha256};
17use thiserror::Error;
18use zeroize::Zeroizing;
19
20const KEY_LENGTH: usize = 32;
21const TAG_LENGTH: usize = 16;
22const X25519_OFFSET: usize = 1184;
24
25const SMALL_ORDER_POINTS: [[u8; 32]; 7] = [
28 [0; 32],
29 [
30 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
31 0, 0,
32 ],
33 [
34 224, 235, 122, 124, 59, 65, 184, 174, 22, 86, 227, 250, 241, 159, 196, 106, 218, 9, 141,
35 235, 156, 50, 177, 253, 134, 98, 5, 22, 95, 73, 184, 0,
36 ],
37 [
38 95, 156, 149, 188, 163, 80, 140, 36, 177, 208, 177, 85, 156, 131, 239, 91, 4, 68, 92, 196,
39 88, 28, 142, 134, 216, 34, 78, 221, 208, 159, 17, 87,
40 ],
41 [
42 236, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
43 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127,
44 ],
45 [
46 237, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
47 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127,
48 ],
49 [
50 238, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
51 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127,
52 ],
53];
54const ENCAPSULATION_LENGTH: usize = 1120;
55const WRAPPED_KEY_LENGTH: usize = 48;
56const SUITE: [u8; 2] = 1_u16.to_be_bytes();
57const INFO_PREFIX: &[u8] = b"HIDE/0.1 object-key";
58
59type HpkeSecret = <XWing as Kem>::PrivateKey;
60type HpkePublic = <XWing as Kem>::PublicKey;
61type HpkeEncapsulation = <XWing as Kem>::EncappedKey;
62
63#[derive(Debug, Error)]
65pub enum CryptoError {
66 #[error("cryptographic authentication failed")]
67 Authentication,
68 #[error("recipient public key is degenerate")]
69 DegeneratePublicKey,
70 #[error("invalid cryptographic parameter")]
71 InvalidParameter,
72 #[error("operating-system randomness failed: {0}")]
73 Random(#[from] getrandom::Error),
74 #[error("HPKE operation failed: {0}")]
75 Hpke(#[from] hpke::HpkeError),
76 #[error("invalid {name} length: expected {expected}, got {actual}")]
77 InvalidLength {
78 name: &'static str,
79 expected: usize,
80 actual: usize,
81 },
82}
83
84pub struct ContentKey(Zeroizing<[u8; KEY_LENGTH]>);
96
97impl ContentKey {
98 pub fn generate() -> Result<Self, CryptoError> {
99 Ok(Self(Zeroizing::new(random_array()?)))
100 }
101
102 pub fn from_bytes(bytes: [u8; KEY_LENGTH]) -> Self {
105 Self(Zeroizing::new(bytes))
106 }
107}
108
109pub struct RecipientSecret(Zeroizing<[u8; KEY_LENGTH]>);
121
122impl RecipientSecret {
123 pub fn generate() -> Result<Self, CryptoError> {
124 Ok(Self(Zeroizing::new(random_array()?)))
125 }
126
127 pub fn from_bytes(bytes: &[u8]) -> Result<Self, CryptoError> {
128 require_length("recipient seed", KEY_LENGTH, bytes.len())?;
129 let mut seed = Zeroizing::new([0; KEY_LENGTH]);
130 seed.copy_from_slice(bytes);
131 Ok(Self(seed))
132 }
133
134 pub fn public_key(&self) -> Result<RecipientPublic, CryptoError> {
135 let secret = HpkeSecret::from_bytes(self.0.as_ref())?;
136 Ok(RecipientPublic(XWing::sk_to_pk(&secret)))
137 }
138
139 pub fn expose_seed_for_sealing(&self) -> &[u8] {
142 self.0.as_ref()
143 }
144
145 pub fn export_test_secret(&self) -> Zeroizing<Vec<u8>> {
148 Zeroizing::new(self.0.to_vec())
149 }
150}
151
152#[derive(Clone, Debug)]
154pub struct RecipientPublic(HpkePublic);
155
156impl RecipientPublic {
157 pub fn from_bytes(bytes: &[u8]) -> Result<Self, CryptoError> {
158 let public = Self(HpkePublic::from_bytes(bytes)?);
159 let x25519: [u8; 32] = bytes
160 .get(X25519_OFFSET..)
161 .and_then(|tail| tail.try_into().ok())
162 .ok_or(CryptoError::DegeneratePublicKey)?;
163 if SMALL_ORDER_POINTS.contains(&x25519) {
164 return Err(CryptoError::DegeneratePublicKey);
165 }
166 Ok(public)
167 }
168
169 pub fn to_bytes(&self) -> Vec<u8> {
170 self.0.to_bytes().to_vec()
171 }
172}
173
174pub struct WrappedKey {
176 pub encapsulation: Vec<u8>,
177 pub wrapped_cek: Vec<u8>,
178}
179
180pub fn wrap_cek(
181 recipient: &RecipientPublic,
182 cek: &ContentKey,
183 object_id: &[u8; 32],
184) -> Result<WrappedKey, CryptoError> {
185 let seed = Zeroizing::new(random_array::<32>()?);
186 let mut rng = StdRng::from_seed(*seed);
187 wrap_with_rng(recipient, cek, object_id, &mut rng)
188}
189
190fn wrap_with_rng(
191 recipient: &RecipientPublic,
192 cek: &ContentKey,
193 object_id: &[u8; 32],
194 rng: &mut impl CryptoRng,
195) -> Result<WrappedKey, CryptoError> {
196 let (info, aad) = object_context(object_id);
197 let (encapsulation, mut context) = hpke::setup_sender_with_rng::<HpkeAead, HkdfSha256, XWing>(
198 &OpModeS::Base,
199 &recipient.0,
200 &info,
201 rng,
202 )?;
203 let mut ciphertext = Zeroizing::new(*cek.0);
204 let tag = context.seal_inout_detached(ciphertext.as_mut_slice().into(), &aad)?;
205 let mut wrapped_cek = Vec::with_capacity(WRAPPED_KEY_LENGTH);
206 wrapped_cek.extend_from_slice(ciphertext.as_ref());
207 wrapped_cek.extend_from_slice(&tag.to_bytes());
208 Ok(WrappedKey {
209 encapsulation: encapsulation.to_bytes().to_vec(),
210 wrapped_cek,
211 })
212}
213
214pub fn unwrap_cek(
215 secret: &RecipientSecret,
216 object_id: &[u8; 32],
217 encapsulation: &[u8],
218 wrapped_cek: &[u8],
219) -> Result<ContentKey, CryptoError> {
220 require_length("encapsulation", ENCAPSULATION_LENGTH, encapsulation.len())?;
221 require_length("wrapped CEK", WRAPPED_KEY_LENGTH, wrapped_cek.len())?;
222 let private_key = HpkeSecret::from_bytes(secret.0.as_ref())?;
223 let encapsulation = HpkeEncapsulation::from_bytes(encapsulation)?;
224 let (info, aad) = object_context(object_id);
225 let mut context = hpke::setup_receiver::<HpkeAead, HkdfSha256, XWing>(
226 &OpModeR::Base,
227 &private_key,
228 &encapsulation,
229 &info,
230 )?;
231 let mut plaintext = Zeroizing::new([0; KEY_LENGTH]);
232 plaintext.copy_from_slice(&wrapped_cek[..KEY_LENGTH]);
233 let tag = AeadTag::<HpkeAead>::from_bytes(&wrapped_cek[KEY_LENGTH..])?;
234 context.open_inout_detached(plaintext.as_mut_slice().into(), &aad, &tag)?;
235 Ok(ContentKey(plaintext))
236}
237
238fn object_context(object_id: &[u8; 32]) -> (Vec<u8>, [u8; 34]) {
239 let mut aad = [0; 34];
240 aad[..32].copy_from_slice(object_id);
241 aad[32..].copy_from_slice(&SUITE);
242 let mut info = Vec::with_capacity(INFO_PREFIX.len() + aad.len());
243 info.extend_from_slice(INFO_PREFIX);
244 info.extend_from_slice(&aad);
245 (info, aad)
246}
247
248fn require_length(name: &'static str, expected: usize, actual: usize) -> Result<(), CryptoError> {
249 if actual != expected {
250 return Err(CryptoError::InvalidLength {
251 name,
252 expected,
253 actual,
254 });
255 }
256 Ok(())
257}
258
259pub fn random_array<const LENGTH: usize>() -> Result<[u8; LENGTH], CryptoError> {
260 let mut bytes = Zeroizing::new([0; LENGTH]);
261 getrandom::fill(bytes.as_mut_slice())?;
262 Ok(*bytes)
263}
264
265pub struct DerivedKey(Zeroizing<[u8; KEY_LENGTH]>);
277
278pub struct ChunkCipher(ChaCha20Poly1305);
280
281impl ChunkCipher {
282 pub fn new(key: &DerivedKey) -> Result<Self, CryptoError> {
283 Ok(Self(
284 ChaCha20Poly1305::new_from_slice(key.0.as_ref())
285 .map_err(|_| CryptoError::InvalidParameter)?,
286 ))
287 }
288
289 pub fn seal_in_place(
291 &self,
292 nonce: &[u8; 12],
293 aad: &[u8],
294 buffer: &mut [u8],
295 length: usize,
296 ) -> Result<usize, CryptoError> {
297 let (plaintext, tail) = buffer
298 .split_at_mut_checked(length)
299 .ok_or(CryptoError::InvalidParameter)?;
300 let tag = self
301 .0
302 .encrypt_inout_detached(nonce.into(), aad, plaintext.into())
303 .map_err(|_| CryptoError::Authentication)?;
304 tail.get_mut(..TAG_LENGTH)
305 .ok_or(CryptoError::InvalidParameter)?
306 .copy_from_slice(&tag);
307 Ok(length + TAG_LENGTH)
308 }
309
310 pub fn open_in_place(
312 &self,
313 nonce: &[u8; 12],
314 aad: &[u8],
315 buffer: &mut [u8],
316 ) -> Result<usize, CryptoError> {
317 let length = buffer
318 .len()
319 .checked_sub(TAG_LENGTH)
320 .ok_or(CryptoError::InvalidParameter)?;
321 let (ciphertext, tag) = buffer.split_at_mut(length);
322 let tag =
323 chacha20poly1305::Tag::try_from(&tag[..]).map_err(|_| CryptoError::InvalidParameter)?;
324 self.0
325 .decrypt_inout_detached(nonce.into(), aad, ciphertext.into(), &tag)
326 .map_err(|_| CryptoError::Authentication)?;
327 Ok(length)
328 }
329}
330
331pub fn derive_key(cek: &ContentKey, salt: &[u8], info: &[u8]) -> Result<DerivedKey, CryptoError> {
332 let mut key = Zeroizing::new([0; KEY_LENGTH]);
333 Hkdf::<Sha256>::new(Some(salt), cek.0.as_ref())
334 .expand(info, key.as_mut_slice())
335 .map_err(|_| CryptoError::InvalidParameter)?;
336 Ok(DerivedKey(key))
337}
338
339pub fn seal(
340 key: &DerivedKey,
341 nonce: &[u8; 12],
342 aad: &[u8],
343 plaintext: &[u8],
344) -> Result<Vec<u8>, CryptoError> {
345 let cipher = ChaCha20Poly1305::new_from_slice(key.0.as_ref())
346 .map_err(|_| CryptoError::InvalidParameter)?;
347 let mut buffer = Zeroizing::new(Vec::with_capacity(plaintext.len() + TAG_LENGTH));
348 buffer.extend_from_slice(plaintext);
349 cipher
350 .encrypt_in_place(nonce.into(), aad, &mut *buffer)
351 .map_err(|_| CryptoError::Authentication)?;
352 Ok(core::mem::take(&mut *buffer))
353}
354
355pub fn open(
356 key: &DerivedKey,
357 nonce: &[u8; 12],
358 aad: &[u8],
359 ciphertext: &[u8],
360) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
361 let cipher = ChaCha20Poly1305::new_from_slice(key.0.as_ref())
362 .map_err(|_| CryptoError::InvalidParameter)?;
363 let mut buffer = Zeroizing::new(ciphertext.to_vec());
364 cipher
365 .decrypt_in_place(nonce.into(), aad, &mut *buffer)
366 .map_err(|_| CryptoError::Authentication)?;
367 Ok(buffer)
368}
369
370fn mac_state(key: &DerivedKey, parts: &[&[u8]]) -> Result<Hmac<Sha256>, CryptoError> {
371 let mut state = <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(key.0.as_ref())
372 .map_err(|_| CryptoError::InvalidParameter)?;
373 for part in parts {
374 state.update(part);
375 }
376 Ok(state)
377}
378
379pub fn mac(key: &DerivedKey, parts: &[&[u8]]) -> Result<[u8; 32], CryptoError> {
380 Ok(mac_state(key, parts)?.finalize().into_bytes().into())
381}
382
383pub fn verify_mac(key: &DerivedKey, parts: &[&[u8]], tag: &[u8; 32]) -> Result<(), CryptoError> {
384 mac_state(key, parts)?
385 .verify_slice(tag)
386 .map_err(|_| CryptoError::Authentication)
387}
388
389pub fn hash(parts: &[&[u8]]) -> [u8; 32] {
390 let mut state = Sha256::new();
391 for part in parts {
392 state.update(part);
393 }
394 state.finalize().into()
395}
396
397#[derive(Default)]
399pub struct Hasher(Sha256);
400
401impl Hasher {
402 pub fn new() -> Self {
403 Self(Sha256::new())
404 }
405
406 pub fn update(&mut self, bytes: &[u8]) {
407 self.0.update(bytes);
408 }
409
410 pub fn finish(self) -> [u8; 32] {
411 self.0.finalize().into()
412 }
413}
414
415#[cfg(feature = "test-vectors")]
416pub fn wrap_cek_for_vector(
417 recipient: &RecipientPublic,
418 cek: &ContentKey,
419 object_id: &[u8; 32],
420 seed: [u8; 32],
421) -> Result<WrappedKey, CryptoError> {
422 wrap_with_rng(recipient, cek, object_id, &mut StdRng::from_seed(seed))
423}
424
425#[cfg(test)]
426mod tests {
427 use super::*;
428
429 #[test]
430 fn rejects_wrong_recipient_context_and_tampering() -> Result<(), CryptoError> {
431 let recipient = RecipientSecret::generate()?;
432 let other = RecipientSecret::generate()?;
433 let cek = ContentKey::generate()?;
434 let mut wrapped = wrap_cek(&recipient.public_key()?, &cek, &[1; 32])?;
435 assert!(
436 unwrap_cek(
437 &other,
438 &[1; 32],
439 &wrapped.encapsulation,
440 &wrapped.wrapped_cek
441 )
442 .is_err()
443 );
444 assert!(
445 unwrap_cek(
446 &recipient,
447 &[2; 32],
448 &wrapped.encapsulation,
449 &wrapped.wrapped_cek
450 )
451 .is_err()
452 );
453 wrapped.encapsulation[0] ^= 1;
454 assert!(
455 unwrap_cek(
456 &recipient,
457 &[1; 32],
458 &wrapped.encapsulation,
459 &wrapped.wrapped_cek
460 )
461 .is_err()
462 );
463 wrapped.encapsulation[0] ^= 1;
464 wrapped.wrapped_cek[0] ^= 1;
465 assert!(
466 unwrap_cek(
467 &recipient,
468 &[1; 32],
469 &wrapped.encapsulation,
470 &wrapped.wrapped_cek
471 )
472 .is_err()
473 );
474 Ok(())
475 }
476
477 #[test]
478 fn rfc5869_hkdf_known_answer() -> Result<(), CryptoError> {
479 let salt: Vec<u8> = (0..13).collect();
480 let info: Vec<u8> = (0xf0..=0xf9).collect();
481 let mut output = [0; 42];
482 Hkdf::<Sha256>::new(Some(&salt), &[0x0b; 22])
483 .expand(&info, &mut output)
484 .map_err(|_| CryptoError::InvalidParameter)?;
485 assert_eq!(
486 output,
487 [
488 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36,
489 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56,
490 0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65
491 ]
492 );
493 Ok(())
494 }
495
496 #[test]
497 fn rfc4231_hmac_known_answer_and_bad_tag() -> Result<(), CryptoError> {
498 let mut bytes = [0; 32];
499 bytes[..20].fill(0x0b);
500 let key = DerivedKey(Zeroizing::new(bytes));
501 let expected = [
502 0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b,
503 0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c,
504 0x2e, 0x32, 0xcf, 0xf7,
505 ];
506 assert_eq!(mac(&key, &[b"Hi There"])?, expected);
507 verify_mac(&key, &[b"Hi There"], &expected)?;
508 assert!(verify_mac(&key, &[b"Hi there"], &expected).is_err());
509 Ok(())
510 }
511
512 #[test]
513 fn aead_authenticates_nonce_aad_and_ciphertext() -> Result<(), CryptoError> {
514 let cek = ContentKey::generate()?;
515 let key = derive_key(&cek, b"salt", b"purpose")?;
516 let mut ciphertext = seal(&key, &[0; 12], b"aad", b"payload")?;
517 assert_eq!(&*open(&key, &[0; 12], b"aad", &ciphertext)?, b"payload");
518 assert!(open(&key, &[1; 12], b"aad", &ciphertext).is_err());
519 assert!(open(&key, &[0; 12], b"other", &ciphertext).is_err());
520 ciphertext[0] ^= 1;
521 assert!(open(&key, &[0; 12], b"aad", &ciphertext).is_err());
522 Ok(())
523 }
524
525 #[test]
526 fn in_place_cipher_matches_allocating_api() -> Result<(), CryptoError> {
527 let cek = ContentKey::generate()?;
528 let key = derive_key(&cek, b"salt", b"purpose")?;
529 let cipher = ChunkCipher::new(&key)?;
530 for length in [0, 1, 64, 4096] {
531 let plaintext = vec![0x33; length];
532 let mut buffer = vec![0; length + TAG_LENGTH];
533 buffer[..length].copy_from_slice(&plaintext);
534 let sealed = cipher.seal_in_place(&[9; 12], b"aad", &mut buffer, length)?;
535 assert_eq!(buffer[..sealed], *seal(&key, &[9; 12], b"aad", &plaintext)?);
536 assert_eq!(
537 cipher.open_in_place(&[9; 12], b"aad", &mut buffer[..sealed])?,
538 length
539 );
540 assert_eq!(buffer[..length], *plaintext);
541 assert!(
542 cipher
543 .open_in_place(&[8; 12], b"aad", &mut buffer[..sealed])
544 .is_err()
545 );
546 assert!(
547 cipher
548 .open_in_place(&[9; 12], b"bad", &mut buffer[..sealed])
549 .is_err()
550 );
551 }
552 assert!(
553 cipher
554 .open_in_place(&[9; 12], b"aad", &mut [0; 15])
555 .is_err()
556 );
557 assert!(
558 cipher
559 .seal_in_place(&[9; 12], b"aad", &mut [0; 8], 4)
560 .is_err()
561 );
562 Ok(())
563 }
564
565 #[test]
566 fn rejects_small_order_x25519_public_keys() -> Result<(), CryptoError> {
567 let genuine = RecipientSecret::from_bytes(&[0x21; 32])?
568 .public_key()?
569 .to_bytes();
570 assert!(RecipientPublic::from_bytes(&genuine).is_ok());
571 for point in SMALL_ORDER_POINTS {
572 let mut bytes = genuine.clone();
573 bytes[X25519_OFFSET..].copy_from_slice(&point);
574 assert!(
575 matches!(
576 RecipientPublic::from_bytes(&bytes),
577 Err(CryptoError::DegeneratePublicKey)
578 ),
579 "accepted small-order point {point:?}"
580 );
581 }
582 assert!(RecipientPublic::from_bytes(&genuine[..1215]).is_err());
583 assert!(RecipientPublic::from_bytes(&[]).is_err());
584 Ok(())
585 }
586
587 #[test]
588 fn suite_sizes_and_random_roundtrip() -> Result<(), CryptoError> {
589 assert_eq!(XWing::KEM_ID, 0x647a);
590 assert_eq!(HpkeSecret::size(), 32);
591 assert_eq!(HpkePublic::size(), 1216);
592 assert_eq!(HpkeEncapsulation::size(), 1120);
593 let recipient = RecipientSecret::generate()?;
594 let public = RecipientPublic::from_bytes(&recipient.public_key()?.to_bytes())?;
595 let cek = ContentKey::generate()?;
596 let object_id = random_array()?;
597 let wrapped = wrap_cek(&public, &cek, &object_id)?;
598 assert_eq!(wrapped.encapsulation.len(), 1120);
599 assert_eq!(wrapped.wrapped_cek.len(), 48);
600 let opened = unwrap_cek(
601 &recipient,
602 &object_id,
603 &wrapped.encapsulation,
604 &wrapped.wrapped_cek,
605 )?;
606 assert_eq!(*cek.0, *opened.0);
607 Ok(())
608 }
609
610 #[test]
611 fn raw_seed_import_export() -> Result<(), CryptoError> {
612 let seed = [0x42; 32];
613 let recipient = RecipientSecret::from_bytes(&seed)?;
614 let direct = HpkeSecret::from_bytes(&seed)?;
615 assert_eq!(&*recipient.export_test_secret(), &seed);
616 assert_eq!(
617 recipient.public_key()?.to_bytes(),
618 XWing::sk_to_pk(&direct).to_bytes().to_vec()
619 );
620 assert!(RecipientSecret::from_bytes(&seed[..31]).is_err());
621 assert!(RecipientSecret::from_bytes(&[0; 33]).is_err());
622 Ok(())
623 }
624}