Skip to main content

hide_crypto/
lib.rs

1//! Local cryptographic primitives for the experimental HIDE/0.1 format.
2//!
3//! Suite 1 is HPKE base mode with X-Wing, HKDF-SHA256, and ChaCha20-Poly1305.
4//! This crate is unaudited and makes no anonymity or forward-secrecy guarantee.
5
6use 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;
22/// X-Wing public keys are ML-KEM-768 (1184) || X25519 (32).
23const X25519_OFFSET: usize = 1184;
24
25/// Curve25519 points of order < 8 (RFC 7748 §6.1); each forces an all-zero X25519
26/// shared secret, so the classical half of the hybrid would contribute nothing.
27const 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/// An error that contains no secret key material or plaintext.
64#[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
84/// A zeroizing content-encryption key, intentionally not Debug or Clone.
85///
86/// ```compile_fail,E0277
87/// fn requires_debug<T: core::fmt::Debug>() {}
88/// requires_debug::<hide_crypto::ContentKey>();
89/// ```
90///
91/// ```compile_fail,E0277
92/// fn requires_clone<T: Clone>() {}
93/// requires_clone::<hide_crypto::ContentKey>();
94/// ```
95pub 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    /// Imports known bytes for deterministic test inputs only.
103    /// Production callers must use `generate`; this cannot erase caller copies.
104    pub fn from_bytes(bytes: [u8; KEY_LENGTH]) -> Self {
105        Self(Zeroizing::new(bytes))
106    }
107}
108
109/// A zeroizing raw X-Wing seed, not HPKE `DeriveKeyPair` input material.
110///
111/// ```compile_fail,E0277
112/// fn requires_debug<T: core::fmt::Debug>() {}
113/// requires_debug::<hide_crypto::RecipientSecret>();
114/// ```
115///
116/// ```compile_fail,E0277
117/// fn requires_clone<T: Clone>() {}
118/// requires_clone::<hide_crypto::RecipientSecret>();
119/// ```
120pub 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    /// Exposes the raw seed so it can be sealed for storage. Deliberately named
140    /// to make a plaintext write of the result look wrong at the call site.
141    pub fn expose_seed_for_sealing(&self) -> &[u8] {
142        self.0.as_ref()
143    }
144
145    /// Explicit secret export for this experimental CLI only.
146    /// The caller must protect the result and avoid logging or copying it.
147    pub fn export_test_secret(&self) -> Zeroizing<Vec<u8>> {
148        Zeroizing::new(self.0.to_vec())
149    }
150}
151
152/// An HPKE-validated X-Wing recipient public key.
153#[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        // RFC 7748 decoders mask bit 255 and reduce mod p, so a non-canonical
167        // encoding names the same point as a canonical one, including the
168        // small-order ones the list above compares by bytes (spec §9.5).
169        // No honest X25519 implementation produces such an encoding.
170        if !is_canonical_x25519(&x25519) {
171            return Err(CryptoError::DegeneratePublicKey);
172        }
173        Ok(public)
174    }
175
176    pub fn to_bytes(&self) -> Vec<u8> {
177        self.0.to_bytes().to_vec()
178    }
179}
180
181/// Whether a little-endian X25519 u-coordinate is in canonical form: bit 255
182/// clear and the value below p = 2^255 - 19. With bit 255 clear the only
183/// non-canonical values are p ..= 2^255 - 1, i.e. `ed..ff ff..ff 7f`.
184fn is_canonical_x25519(bytes: &[u8; 32]) -> bool {
185    if bytes[31] & 0x80 != 0 {
186        return false;
187    }
188    let at_least_p =
189        bytes[31] == 0x7f && bytes[1..31].iter().all(|&byte| byte == 0xff) && bytes[0] >= 0xed;
190    !at_least_p
191}
192
193/// Suite-1 encapsulation and authenticated encryption of a 32-byte CEK.
194pub struct WrappedKey {
195    pub encapsulation: Vec<u8>,
196    pub wrapped_cek: Vec<u8>,
197}
198
199pub fn wrap_cek(
200    recipient: &RecipientPublic,
201    cek: &ContentKey,
202    object_id: &[u8; 32],
203) -> Result<WrappedKey, CryptoError> {
204    let seed = Zeroizing::new(random_array::<32>()?);
205    let mut rng = StdRng::from_seed(*seed);
206    wrap_with_rng(recipient, cek, object_id, &mut rng)
207}
208
209fn wrap_with_rng(
210    recipient: &RecipientPublic,
211    cek: &ContentKey,
212    object_id: &[u8; 32],
213    rng: &mut impl CryptoRng,
214) -> Result<WrappedKey, CryptoError> {
215    let (info, aad) = object_context(object_id);
216    let (encapsulation, mut context) = hpke::setup_sender_with_rng::<HpkeAead, HkdfSha256, XWing>(
217        &OpModeS::Base,
218        &recipient.0,
219        &info,
220        rng,
221    )?;
222    let mut ciphertext = Zeroizing::new(*cek.0);
223    let tag = context.seal_inout_detached(ciphertext.as_mut_slice().into(), &aad)?;
224    let mut wrapped_cek = Vec::with_capacity(WRAPPED_KEY_LENGTH);
225    wrapped_cek.extend_from_slice(ciphertext.as_ref());
226    wrapped_cek.extend_from_slice(&tag.to_bytes());
227    Ok(WrappedKey {
228        encapsulation: encapsulation.to_bytes().to_vec(),
229        wrapped_cek,
230    })
231}
232
233pub fn unwrap_cek(
234    secret: &RecipientSecret,
235    object_id: &[u8; 32],
236    encapsulation: &[u8],
237    wrapped_cek: &[u8],
238) -> Result<ContentKey, CryptoError> {
239    require_length("encapsulation", ENCAPSULATION_LENGTH, encapsulation.len())?;
240    require_length("wrapped CEK", WRAPPED_KEY_LENGTH, wrapped_cek.len())?;
241    let private_key = HpkeSecret::from_bytes(secret.0.as_ref())?;
242    let encapsulation = HpkeEncapsulation::from_bytes(encapsulation)?;
243    let (info, aad) = object_context(object_id);
244    let mut context = hpke::setup_receiver::<HpkeAead, HkdfSha256, XWing>(
245        &OpModeR::Base,
246        &private_key,
247        &encapsulation,
248        &info,
249    )?;
250    let mut plaintext = Zeroizing::new([0; KEY_LENGTH]);
251    plaintext.copy_from_slice(&wrapped_cek[..KEY_LENGTH]);
252    let tag = AeadTag::<HpkeAead>::from_bytes(&wrapped_cek[KEY_LENGTH..])?;
253    context.open_inout_detached(plaintext.as_mut_slice().into(), &aad, &tag)?;
254    Ok(ContentKey(plaintext))
255}
256
257fn object_context(object_id: &[u8; 32]) -> (Vec<u8>, [u8; 34]) {
258    let mut aad = [0; 34];
259    aad[..32].copy_from_slice(object_id);
260    aad[32..].copy_from_slice(&SUITE);
261    let mut info = Vec::with_capacity(INFO_PREFIX.len() + aad.len());
262    info.extend_from_slice(INFO_PREFIX);
263    info.extend_from_slice(&aad);
264    (info, aad)
265}
266
267fn require_length(name: &'static str, expected: usize, actual: usize) -> Result<(), CryptoError> {
268    if actual != expected {
269        return Err(CryptoError::InvalidLength {
270            name,
271            expected,
272            actual,
273        });
274    }
275    Ok(())
276}
277
278pub fn random_array<const LENGTH: usize>() -> Result<[u8; LENGTH], CryptoError> {
279    let mut bytes = Zeroizing::new([0; LENGTH]);
280    getrandom::fill(bytes.as_mut_slice())?;
281    Ok(*bytes)
282}
283
284/// A purpose-bound key derived from the content key; not Debug or Clone.
285///
286/// ```compile_fail,E0277
287/// fn requires_debug<T: core::fmt::Debug>() {}
288/// requires_debug::<hide_crypto::DerivedKey>();
289/// ```
290///
291/// ```compile_fail,E0277
292/// fn requires_clone<T: Clone>() {}
293/// requires_clone::<hide_crypto::DerivedKey>();
294/// ```
295pub struct DerivedKey(Zeroizing<[u8; KEY_LENGTH]>);
296
297/// Keeps one expanded AEAD instance so streaming does not rekey per chunk.
298pub struct ChunkCipher(ChaCha20Poly1305);
299
300impl ChunkCipher {
301    pub fn new(key: &DerivedKey) -> Result<Self, CryptoError> {
302        Ok(Self(
303            ChaCha20Poly1305::new_from_slice(key.0.as_ref())
304                .map_err(|_| CryptoError::InvalidParameter)?,
305        ))
306    }
307
308    /// Encrypts `buffer[..length]` in place and appends the tag, returning the ciphertext length.
309    pub fn seal_in_place(
310        &self,
311        nonce: &[u8; 12],
312        aad: &[u8],
313        buffer: &mut [u8],
314        length: usize,
315    ) -> Result<usize, CryptoError> {
316        let (plaintext, tail) = buffer
317            .split_at_mut_checked(length)
318            .ok_or(CryptoError::InvalidParameter)?;
319        let tag = self
320            .0
321            .encrypt_inout_detached(nonce.into(), aad, plaintext.into())
322            .map_err(|_| CryptoError::Authentication)?;
323        tail.get_mut(..TAG_LENGTH)
324            .ok_or(CryptoError::InvalidParameter)?
325            .copy_from_slice(&tag);
326        Ok(length + TAG_LENGTH)
327    }
328
329    /// Decrypts `buffer` in place, returning the authenticated plaintext length.
330    pub fn open_in_place(
331        &self,
332        nonce: &[u8; 12],
333        aad: &[u8],
334        buffer: &mut [u8],
335    ) -> Result<usize, CryptoError> {
336        let length = buffer
337            .len()
338            .checked_sub(TAG_LENGTH)
339            .ok_or(CryptoError::InvalidParameter)?;
340        let (ciphertext, tag) = buffer.split_at_mut(length);
341        let tag =
342            chacha20poly1305::Tag::try_from(&tag[..]).map_err(|_| CryptoError::InvalidParameter)?;
343        self.0
344            .decrypt_inout_detached(nonce.into(), aad, ciphertext.into(), &tag)
345            .map_err(|_| CryptoError::Authentication)?;
346        Ok(length)
347    }
348}
349
350pub fn derive_key(cek: &ContentKey, salt: &[u8], info: &[u8]) -> Result<DerivedKey, CryptoError> {
351    let mut key = Zeroizing::new([0; KEY_LENGTH]);
352    Hkdf::<Sha256>::new(Some(salt), cek.0.as_ref())
353        .expand(info, key.as_mut_slice())
354        .map_err(|_| CryptoError::InvalidParameter)?;
355    Ok(DerivedKey(key))
356}
357
358pub fn seal(
359    key: &DerivedKey,
360    nonce: &[u8; 12],
361    aad: &[u8],
362    plaintext: &[u8],
363) -> Result<Vec<u8>, CryptoError> {
364    let cipher = ChaCha20Poly1305::new_from_slice(key.0.as_ref())
365        .map_err(|_| CryptoError::InvalidParameter)?;
366    let mut buffer = Zeroizing::new(Vec::with_capacity(plaintext.len() + TAG_LENGTH));
367    buffer.extend_from_slice(plaintext);
368    cipher
369        .encrypt_in_place(nonce.into(), aad, &mut *buffer)
370        .map_err(|_| CryptoError::Authentication)?;
371    Ok(core::mem::take(&mut *buffer))
372}
373
374pub fn open(
375    key: &DerivedKey,
376    nonce: &[u8; 12],
377    aad: &[u8],
378    ciphertext: &[u8],
379) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
380    let cipher = ChaCha20Poly1305::new_from_slice(key.0.as_ref())
381        .map_err(|_| CryptoError::InvalidParameter)?;
382    let mut buffer = Zeroizing::new(ciphertext.to_vec());
383    cipher
384        .decrypt_in_place(nonce.into(), aad, &mut *buffer)
385        .map_err(|_| CryptoError::Authentication)?;
386    Ok(buffer)
387}
388
389fn mac_state(key: &DerivedKey, parts: &[&[u8]]) -> Result<Hmac<Sha256>, CryptoError> {
390    let mut state = <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(key.0.as_ref())
391        .map_err(|_| CryptoError::InvalidParameter)?;
392    for part in parts {
393        state.update(part);
394    }
395    Ok(state)
396}
397
398pub fn mac(key: &DerivedKey, parts: &[&[u8]]) -> Result<[u8; 32], CryptoError> {
399    Ok(mac_state(key, parts)?.finalize().into_bytes().into())
400}
401
402pub fn verify_mac(key: &DerivedKey, parts: &[&[u8]], tag: &[u8; 32]) -> Result<(), CryptoError> {
403    mac_state(key, parts)?
404        .verify_slice(tag)
405        .map_err(|_| CryptoError::Authentication)
406}
407
408pub fn hash(parts: &[&[u8]]) -> [u8; 32] {
409    let mut state = Sha256::new();
410    for part in parts {
411        state.update(part);
412    }
413    state.finalize().into()
414}
415
416/// Incremental form of [`hash`], for data that arrives in pieces.
417#[derive(Default)]
418pub struct Hasher(Sha256);
419
420impl Hasher {
421    pub fn new() -> Self {
422        Self(Sha256::new())
423    }
424
425    pub fn update(&mut self, bytes: &[u8]) {
426        self.0.update(bytes);
427    }
428
429    pub fn finish(self) -> [u8; 32] {
430        self.0.finalize().into()
431    }
432}
433
434#[cfg(feature = "test-vectors")]
435pub fn wrap_cek_for_vector(
436    recipient: &RecipientPublic,
437    cek: &ContentKey,
438    object_id: &[u8; 32],
439    seed: [u8; 32],
440) -> Result<WrappedKey, CryptoError> {
441    wrap_with_rng(recipient, cek, object_id, &mut StdRng::from_seed(seed))
442}
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447
448    #[test]
449    fn rejects_wrong_recipient_context_and_tampering() -> Result<(), CryptoError> {
450        let recipient = RecipientSecret::generate()?;
451        let other = RecipientSecret::generate()?;
452        let cek = ContentKey::generate()?;
453        let mut wrapped = wrap_cek(&recipient.public_key()?, &cek, &[1; 32])?;
454        assert!(
455            unwrap_cek(
456                &other,
457                &[1; 32],
458                &wrapped.encapsulation,
459                &wrapped.wrapped_cek
460            )
461            .is_err()
462        );
463        assert!(
464            unwrap_cek(
465                &recipient,
466                &[2; 32],
467                &wrapped.encapsulation,
468                &wrapped.wrapped_cek
469            )
470            .is_err()
471        );
472        wrapped.encapsulation[0] ^= 1;
473        assert!(
474            unwrap_cek(
475                &recipient,
476                &[1; 32],
477                &wrapped.encapsulation,
478                &wrapped.wrapped_cek
479            )
480            .is_err()
481        );
482        wrapped.encapsulation[0] ^= 1;
483        wrapped.wrapped_cek[0] ^= 1;
484        assert!(
485            unwrap_cek(
486                &recipient,
487                &[1; 32],
488                &wrapped.encapsulation,
489                &wrapped.wrapped_cek
490            )
491            .is_err()
492        );
493        Ok(())
494    }
495
496    #[test]
497    fn rfc5869_hkdf_known_answer() -> Result<(), CryptoError> {
498        let salt: Vec<u8> = (0..13).collect();
499        let info: Vec<u8> = (0xf0..=0xf9).collect();
500        let mut output = [0; 42];
501        Hkdf::<Sha256>::new(Some(&salt), &[0x0b; 22])
502            .expand(&info, &mut output)
503            .map_err(|_| CryptoError::InvalidParameter)?;
504        assert_eq!(
505            output,
506            [
507                0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36,
508                0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56,
509                0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65
510            ]
511        );
512        Ok(())
513    }
514
515    #[test]
516    fn rfc4231_hmac_known_answer_and_bad_tag() -> Result<(), CryptoError> {
517        let mut bytes = [0; 32];
518        bytes[..20].fill(0x0b);
519        let key = DerivedKey(Zeroizing::new(bytes));
520        let expected = [
521            0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b,
522            0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c,
523            0x2e, 0x32, 0xcf, 0xf7,
524        ];
525        assert_eq!(mac(&key, &[b"Hi There"])?, expected);
526        verify_mac(&key, &[b"Hi There"], &expected)?;
527        assert!(verify_mac(&key, &[b"Hi there"], &expected).is_err());
528        Ok(())
529    }
530
531    #[test]
532    fn aead_authenticates_nonce_aad_and_ciphertext() -> Result<(), CryptoError> {
533        let cek = ContentKey::generate()?;
534        let key = derive_key(&cek, b"salt", b"purpose")?;
535        let mut ciphertext = seal(&key, &[0; 12], b"aad", b"payload")?;
536        assert_eq!(&*open(&key, &[0; 12], b"aad", &ciphertext)?, b"payload");
537        assert!(open(&key, &[1; 12], b"aad", &ciphertext).is_err());
538        assert!(open(&key, &[0; 12], b"other", &ciphertext).is_err());
539        ciphertext[0] ^= 1;
540        assert!(open(&key, &[0; 12], b"aad", &ciphertext).is_err());
541        Ok(())
542    }
543
544    #[test]
545    fn in_place_cipher_matches_allocating_api() -> Result<(), CryptoError> {
546        let cek = ContentKey::generate()?;
547        let key = derive_key(&cek, b"salt", b"purpose")?;
548        let cipher = ChunkCipher::new(&key)?;
549        for length in [0, 1, 64, 4096] {
550            let plaintext = vec![0x33; length];
551            let mut buffer = vec![0; length + TAG_LENGTH];
552            buffer[..length].copy_from_slice(&plaintext);
553            let sealed = cipher.seal_in_place(&[9; 12], b"aad", &mut buffer, length)?;
554            assert_eq!(buffer[..sealed], *seal(&key, &[9; 12], b"aad", &plaintext)?);
555            assert_eq!(
556                cipher.open_in_place(&[9; 12], b"aad", &mut buffer[..sealed])?,
557                length
558            );
559            assert_eq!(buffer[..length], *plaintext);
560            assert!(
561                cipher
562                    .open_in_place(&[8; 12], b"aad", &mut buffer[..sealed])
563                    .is_err()
564            );
565            assert!(
566                cipher
567                    .open_in_place(&[9; 12], b"bad", &mut buffer[..sealed])
568                    .is_err()
569            );
570        }
571        assert!(
572            cipher
573                .open_in_place(&[9; 12], b"aad", &mut [0; 15])
574                .is_err()
575        );
576        assert!(
577            cipher
578                .seal_in_place(&[9; 12], b"aad", &mut [0; 8], 4)
579                .is_err()
580        );
581        Ok(())
582    }
583
584    #[test]
585    fn rejects_small_order_x25519_public_keys() -> Result<(), CryptoError> {
586        let genuine = RecipientSecret::from_bytes(&[0x21; 32])?
587            .public_key()?
588            .to_bytes();
589        assert!(RecipientPublic::from_bytes(&genuine).is_ok());
590        for point in SMALL_ORDER_POINTS {
591            let mut bytes = genuine.clone();
592            bytes[X25519_OFFSET..].copy_from_slice(&point);
593            assert!(
594                matches!(
595                    RecipientPublic::from_bytes(&bytes),
596                    Err(CryptoError::DegeneratePublicKey)
597                ),
598                "accepted small-order point {point:?}"
599            );
600        }
601        assert!(RecipientPublic::from_bytes(&genuine[..1215]).is_err());
602        assert!(RecipientPublic::from_bytes(&[]).is_err());
603        Ok(())
604    }
605
606    /// §15.7 closed: the small-order list compares bytes, so the same points
607    /// with bit 255 set, or reduced values >= p, used to pass it.
608    #[test]
609    fn rejects_non_canonical_x25519_encodings() -> Result<(), CryptoError> {
610        let genuine = RecipientSecret::from_bytes(&[0x21; 32])?
611            .public_key()?
612            .to_bytes();
613        let mut high_bit_genuine = genuine.clone();
614        high_bit_genuine[1215] |= 0x80;
615        let mut p_minus_one = [0xff_u8; 32];
616        p_minus_one[0] = 0xec;
617        p_minus_one[31] = 0x7f;
618
619        let mut cases: Vec<[u8; 32]> = Vec::new();
620        for point in SMALL_ORDER_POINTS {
621            let mut high = point;
622            high[31] |= 0x80;
623            cases.push(high);
624        }
625        for low in [0xed_u8, 0xee, 0xef, 0xf0, 0xfe, 0xff] {
626            let mut value = p_minus_one;
627            value[0] = low;
628            cases.push(value);
629        }
630        for x25519 in cases {
631            let mut bytes = genuine.clone();
632            bytes[X25519_OFFSET..].copy_from_slice(&x25519);
633            assert!(
634                matches!(
635                    RecipientPublic::from_bytes(&bytes),
636                    Err(CryptoError::DegeneratePublicKey)
637                ),
638                "accepted non-canonical {x25519:02x?}"
639            );
640        }
641        assert!(matches!(
642            RecipientPublic::from_bytes(&high_bit_genuine),
643            Err(CryptoError::DegeneratePublicKey)
644        ));
645        // p - 1 is canonical (and small-order, refused by the list); the
646        // boundary must sit exactly at p.
647        assert!(is_canonical_x25519(&p_minus_one));
648        let mut p = p_minus_one;
649        p[0] = 0xed;
650        assert!(!is_canonical_x25519(&p));
651        Ok(())
652    }
653
654    /// Every honestly generated key is canonical, so the new rule cannot
655    /// refuse a real recipient.
656    #[test]
657    fn generated_keys_are_always_canonical() -> Result<(), CryptoError> {
658        for _ in 0..256 {
659            let public = RecipientSecret::generate()?.public_key()?.to_bytes();
660            RecipientPublic::from_bytes(&public)?;
661        }
662        Ok(())
663    }
664
665    #[test]
666    fn suite_sizes_and_random_roundtrip() -> Result<(), CryptoError> {
667        assert_eq!(XWing::KEM_ID, 0x647a);
668        assert_eq!(HpkeSecret::size(), 32);
669        assert_eq!(HpkePublic::size(), 1216);
670        assert_eq!(HpkeEncapsulation::size(), 1120);
671        let recipient = RecipientSecret::generate()?;
672        let public = RecipientPublic::from_bytes(&recipient.public_key()?.to_bytes())?;
673        let cek = ContentKey::generate()?;
674        let object_id = random_array()?;
675        let wrapped = wrap_cek(&public, &cek, &object_id)?;
676        assert_eq!(wrapped.encapsulation.len(), 1120);
677        assert_eq!(wrapped.wrapped_cek.len(), 48);
678        let opened = unwrap_cek(
679            &recipient,
680            &object_id,
681            &wrapped.encapsulation,
682            &wrapped.wrapped_cek,
683        )?;
684        assert_eq!(*cek.0, *opened.0);
685        Ok(())
686    }
687
688    #[test]
689    fn raw_seed_import_export() -> Result<(), CryptoError> {
690        let seed = [0x42; 32];
691        let recipient = RecipientSecret::from_bytes(&seed)?;
692        let direct = HpkeSecret::from_bytes(&seed)?;
693        assert_eq!(&*recipient.export_test_secret(), &seed);
694        assert_eq!(
695            recipient.public_key()?.to_bytes(),
696            XWing::sk_to_pk(&direct).to_bytes().to_vec()
697        );
698        assert!(RecipientSecret::from_bytes(&seed[..31]).is_err());
699        assert!(RecipientSecret::from_bytes(&[0; 33]).is_err());
700        Ok(())
701    }
702}