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]>);
266
267pub struct ChunkCipher(ChaCha20Poly1305);
269
270impl ChunkCipher {
271 pub fn new(key: &DerivedKey) -> Result<Self, CryptoError> {
272 Ok(Self(
273 ChaCha20Poly1305::new_from_slice(key.0.as_ref())
274 .map_err(|_| CryptoError::InvalidParameter)?,
275 ))
276 }
277
278 pub fn seal_in_place(
280 &self,
281 nonce: &[u8; 12],
282 aad: &[u8],
283 buffer: &mut [u8],
284 length: usize,
285 ) -> Result<usize, CryptoError> {
286 let (plaintext, tail) = buffer
287 .split_at_mut_checked(length)
288 .ok_or(CryptoError::InvalidParameter)?;
289 let tag = self
290 .0
291 .encrypt_inout_detached(nonce.into(), aad, plaintext.into())
292 .map_err(|_| CryptoError::Authentication)?;
293 tail.get_mut(..TAG_LENGTH)
294 .ok_or(CryptoError::InvalidParameter)?
295 .copy_from_slice(&tag);
296 Ok(length + TAG_LENGTH)
297 }
298
299 pub fn open_in_place(
301 &self,
302 nonce: &[u8; 12],
303 aad: &[u8],
304 buffer: &mut [u8],
305 ) -> Result<usize, CryptoError> {
306 let length = buffer
307 .len()
308 .checked_sub(TAG_LENGTH)
309 .ok_or(CryptoError::InvalidParameter)?;
310 let (ciphertext, tag) = buffer.split_at_mut(length);
311 let tag =
312 chacha20poly1305::Tag::try_from(&tag[..]).map_err(|_| CryptoError::InvalidParameter)?;
313 self.0
314 .decrypt_inout_detached(nonce.into(), aad, ciphertext.into(), &tag)
315 .map_err(|_| CryptoError::Authentication)?;
316 Ok(length)
317 }
318}
319
320pub fn derive_key(cek: &ContentKey, salt: &[u8], info: &[u8]) -> Result<DerivedKey, CryptoError> {
321 let mut key = Zeroizing::new([0; KEY_LENGTH]);
322 Hkdf::<Sha256>::new(Some(salt), cek.0.as_ref())
323 .expand(info, key.as_mut_slice())
324 .map_err(|_| CryptoError::InvalidParameter)?;
325 Ok(DerivedKey(key))
326}
327
328pub fn seal(
329 key: &DerivedKey,
330 nonce: &[u8; 12],
331 aad: &[u8],
332 plaintext: &[u8],
333) -> Result<Vec<u8>, CryptoError> {
334 let cipher = ChaCha20Poly1305::new_from_slice(key.0.as_ref())
335 .map_err(|_| CryptoError::InvalidParameter)?;
336 let mut buffer = Zeroizing::new(Vec::with_capacity(plaintext.len() + TAG_LENGTH));
337 buffer.extend_from_slice(plaintext);
338 cipher
339 .encrypt_in_place(nonce.into(), aad, &mut *buffer)
340 .map_err(|_| CryptoError::Authentication)?;
341 Ok(core::mem::take(&mut *buffer))
342}
343
344pub fn open(
345 key: &DerivedKey,
346 nonce: &[u8; 12],
347 aad: &[u8],
348 ciphertext: &[u8],
349) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
350 let cipher = ChaCha20Poly1305::new_from_slice(key.0.as_ref())
351 .map_err(|_| CryptoError::InvalidParameter)?;
352 let mut buffer = Zeroizing::new(ciphertext.to_vec());
353 cipher
354 .decrypt_in_place(nonce.into(), aad, &mut *buffer)
355 .map_err(|_| CryptoError::Authentication)?;
356 Ok(buffer)
357}
358
359fn mac_state(key: &DerivedKey, parts: &[&[u8]]) -> Result<Hmac<Sha256>, CryptoError> {
360 let mut state = <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(key.0.as_ref())
361 .map_err(|_| CryptoError::InvalidParameter)?;
362 for part in parts {
363 state.update(part);
364 }
365 Ok(state)
366}
367
368pub fn mac(key: &DerivedKey, parts: &[&[u8]]) -> Result<[u8; 32], CryptoError> {
369 Ok(mac_state(key, parts)?.finalize().into_bytes().into())
370}
371
372pub fn verify_mac(key: &DerivedKey, parts: &[&[u8]], tag: &[u8; 32]) -> Result<(), CryptoError> {
373 mac_state(key, parts)?
374 .verify_slice(tag)
375 .map_err(|_| CryptoError::Authentication)
376}
377
378pub fn hash(parts: &[&[u8]]) -> [u8; 32] {
379 let mut state = Sha256::new();
380 for part in parts {
381 state.update(part);
382 }
383 state.finalize().into()
384}
385
386#[derive(Default)]
388pub struct Hasher(Sha256);
389
390impl Hasher {
391 pub fn new() -> Self {
392 Self(Sha256::new())
393 }
394
395 pub fn update(&mut self, bytes: &[u8]) {
396 self.0.update(bytes);
397 }
398
399 pub fn finish(self) -> [u8; 32] {
400 self.0.finalize().into()
401 }
402}
403
404#[cfg(feature = "test-vectors")]
405pub fn wrap_cek_for_vector(
406 recipient: &RecipientPublic,
407 cek: &ContentKey,
408 object_id: &[u8; 32],
409 seed: [u8; 32],
410) -> Result<WrappedKey, CryptoError> {
411 wrap_with_rng(recipient, cek, object_id, &mut StdRng::from_seed(seed))
412}
413
414#[cfg(test)]
415mod tests {
416 use super::*;
417
418 #[test]
419 fn rejects_wrong_recipient_context_and_tampering() -> Result<(), CryptoError> {
420 let recipient = RecipientSecret::generate()?;
421 let other = RecipientSecret::generate()?;
422 let cek = ContentKey::generate()?;
423 let mut wrapped = wrap_cek(&recipient.public_key()?, &cek, &[1; 32])?;
424 assert!(
425 unwrap_cek(
426 &other,
427 &[1; 32],
428 &wrapped.encapsulation,
429 &wrapped.wrapped_cek
430 )
431 .is_err()
432 );
433 assert!(
434 unwrap_cek(
435 &recipient,
436 &[2; 32],
437 &wrapped.encapsulation,
438 &wrapped.wrapped_cek
439 )
440 .is_err()
441 );
442 wrapped.encapsulation[0] ^= 1;
443 assert!(
444 unwrap_cek(
445 &recipient,
446 &[1; 32],
447 &wrapped.encapsulation,
448 &wrapped.wrapped_cek
449 )
450 .is_err()
451 );
452 wrapped.encapsulation[0] ^= 1;
453 wrapped.wrapped_cek[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 Ok(())
464 }
465
466 #[test]
467 fn rfc5869_hkdf_known_answer() -> Result<(), CryptoError> {
468 let salt: Vec<u8> = (0..13).collect();
469 let info: Vec<u8> = (0xf0..=0xf9).collect();
470 let mut output = [0; 42];
471 Hkdf::<Sha256>::new(Some(&salt), &[0x0b; 22])
472 .expand(&info, &mut output)
473 .map_err(|_| CryptoError::InvalidParameter)?;
474 assert_eq!(
475 output,
476 [
477 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36,
478 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56,
479 0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65
480 ]
481 );
482 Ok(())
483 }
484
485 #[test]
486 fn rfc4231_hmac_known_answer_and_bad_tag() -> Result<(), CryptoError> {
487 let mut bytes = [0; 32];
488 bytes[..20].fill(0x0b);
489 let key = DerivedKey(Zeroizing::new(bytes));
490 let expected = [
491 0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b,
492 0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c,
493 0x2e, 0x32, 0xcf, 0xf7,
494 ];
495 assert_eq!(mac(&key, &[b"Hi There"])?, expected);
496 verify_mac(&key, &[b"Hi There"], &expected)?;
497 assert!(verify_mac(&key, &[b"Hi there"], &expected).is_err());
498 Ok(())
499 }
500
501 #[test]
502 fn aead_authenticates_nonce_aad_and_ciphertext() -> Result<(), CryptoError> {
503 let cek = ContentKey::generate()?;
504 let key = derive_key(&cek, b"salt", b"purpose")?;
505 let mut ciphertext = seal(&key, &[0; 12], b"aad", b"payload")?;
506 assert_eq!(&*open(&key, &[0; 12], b"aad", &ciphertext)?, b"payload");
507 assert!(open(&key, &[1; 12], b"aad", &ciphertext).is_err());
508 assert!(open(&key, &[0; 12], b"other", &ciphertext).is_err());
509 ciphertext[0] ^= 1;
510 assert!(open(&key, &[0; 12], b"aad", &ciphertext).is_err());
511 Ok(())
512 }
513
514 #[test]
515 fn in_place_cipher_matches_allocating_api() -> Result<(), CryptoError> {
516 let cek = ContentKey::generate()?;
517 let key = derive_key(&cek, b"salt", b"purpose")?;
518 let cipher = ChunkCipher::new(&key)?;
519 for length in [0, 1, 64, 4096] {
520 let plaintext = vec![0x33; length];
521 let mut buffer = vec![0; length + TAG_LENGTH];
522 buffer[..length].copy_from_slice(&plaintext);
523 let sealed = cipher.seal_in_place(&[9; 12], b"aad", &mut buffer, length)?;
524 assert_eq!(buffer[..sealed], *seal(&key, &[9; 12], b"aad", &plaintext)?);
525 assert_eq!(
526 cipher.open_in_place(&[9; 12], b"aad", &mut buffer[..sealed])?,
527 length
528 );
529 assert_eq!(buffer[..length], *plaintext);
530 assert!(
531 cipher
532 .open_in_place(&[8; 12], b"aad", &mut buffer[..sealed])
533 .is_err()
534 );
535 assert!(
536 cipher
537 .open_in_place(&[9; 12], b"bad", &mut buffer[..sealed])
538 .is_err()
539 );
540 }
541 assert!(
542 cipher
543 .open_in_place(&[9; 12], b"aad", &mut [0; 15])
544 .is_err()
545 );
546 assert!(
547 cipher
548 .seal_in_place(&[9; 12], b"aad", &mut [0; 8], 4)
549 .is_err()
550 );
551 Ok(())
552 }
553
554 #[test]
555 fn rejects_small_order_x25519_public_keys() -> Result<(), CryptoError> {
556 let genuine = RecipientSecret::from_bytes(&[0x21; 32])?
557 .public_key()?
558 .to_bytes();
559 assert!(RecipientPublic::from_bytes(&genuine).is_ok());
560 for point in SMALL_ORDER_POINTS {
561 let mut bytes = genuine.clone();
562 bytes[X25519_OFFSET..].copy_from_slice(&point);
563 assert!(
564 matches!(
565 RecipientPublic::from_bytes(&bytes),
566 Err(CryptoError::DegeneratePublicKey)
567 ),
568 "accepted small-order point {point:?}"
569 );
570 }
571 assert!(RecipientPublic::from_bytes(&genuine[..1215]).is_err());
572 assert!(RecipientPublic::from_bytes(&[]).is_err());
573 Ok(())
574 }
575
576 #[test]
577 fn suite_sizes_and_random_roundtrip() -> Result<(), CryptoError> {
578 assert_eq!(XWing::KEM_ID, 0x647a);
579 assert_eq!(HpkeSecret::size(), 32);
580 assert_eq!(HpkePublic::size(), 1216);
581 assert_eq!(HpkeEncapsulation::size(), 1120);
582 let recipient = RecipientSecret::generate()?;
583 let public = RecipientPublic::from_bytes(&recipient.public_key()?.to_bytes())?;
584 let cek = ContentKey::generate()?;
585 let object_id = random_array()?;
586 let wrapped = wrap_cek(&public, &cek, &object_id)?;
587 assert_eq!(wrapped.encapsulation.len(), 1120);
588 assert_eq!(wrapped.wrapped_cek.len(), 48);
589 let opened = unwrap_cek(
590 &recipient,
591 &object_id,
592 &wrapped.encapsulation,
593 &wrapped.wrapped_cek,
594 )?;
595 assert_eq!(*cek.0, *opened.0);
596 Ok(())
597 }
598
599 #[test]
600 fn raw_seed_import_export() -> Result<(), CryptoError> {
601 let seed = [0x42; 32];
602 let recipient = RecipientSecret::from_bytes(&seed)?;
603 let direct = HpkeSecret::from_bytes(&seed)?;
604 assert_eq!(&*recipient.export_test_secret(), &seed);
605 assert_eq!(
606 recipient.public_key()?.to_bytes(),
607 XWing::sk_to_pk(&direct).to_bytes().to_vec()
608 );
609 assert!(RecipientSecret::from_bytes(&seed[..31]).is_err());
610 assert!(RecipientSecret::from_bytes(&[0; 33]).is_err());
611 Ok(())
612 }
613}