oxicrypto-kex 0.1.0

Pure Rust key exchange implementations for OxiCrypto (X25519)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! [`HpkeSuite`] — the public HPKE API (RFC 9180 §5–§6).
//!
//! An `HpkeSuite` bundles a KEM, KDF, and AEAD and exposes:
//!
//! * key management — [`derive_key_pair`](HpkeSuite::derive_key_pair),
//!   [`generate_key_pair`](HpkeSuite::generate_key_pair);
//! * length accessors — `n_enc`, `n_pk`, `n_sk`, `n_k`, `n_n`, `n_t`;
//! * setup for every mode — `setup_{base,psk,auth,auth_psk}_{s,r}`; and
//! * single-shot [`seal_base`](HpkeSuite::seal_base) / [`open_base`](HpkeSuite::open_base).
//!
//! Sender setup draws a random ephemeral key from an RNG; the `pub(crate)`
//! `*_deterministic` variants take an explicit `ikm_e`, used only by the
//! in-crate known-answer tests.

use oxicrypto_core::{CryptoError, SecretVec};

use super::context::{ContextConfig, HpkeAead, HpkeContextR, HpkeContextS};
use super::ids::{hpke_suite_id, AeadId, KdfId, KemId};
use super::kem::DhKem;
use super::key_schedule::{key_schedule, HpkeMode, KeyScheduleParams};
use super::labeled::HpkeKdf;

/// A complete HPKE ciphersuite: KEM × KDF × AEAD (RFC 9180 §5).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HpkeSuite {
    kem: KemId,
    kdf: KdfId,
    aead: AeadId,
}

impl HpkeSuite {
    /// Construct a suite from its three algorithm identifiers.
    #[must_use]
    pub const fn new(kem: KemId, kdf: KdfId, aead: AeadId) -> Self {
        Self { kem, kdf, aead }
    }

    /// The KEM identifier.
    #[must_use]
    pub const fn kem(self) -> KemId {
        self.kem
    }

    /// The KDF identifier.
    #[must_use]
    pub const fn kdf(self) -> KdfId {
        self.kdf
    }

    /// The AEAD identifier.
    #[must_use]
    pub const fn aead(self) -> AeadId {
        self.aead
    }

    /// `Nenc` — encapsulated-key length in bytes.
    #[must_use]
    pub const fn n_enc(self) -> usize {
        self.kem.n_enc()
    }

    /// `Npk` — serialized public-key length in bytes.
    #[must_use]
    pub const fn n_pk(self) -> usize {
        self.kem.n_pk()
    }

    /// `Nsk` — serialized private-key length in bytes.
    #[must_use]
    pub const fn n_sk(self) -> usize {
        self.kem.n_sk()
    }

    /// `Nk` — AEAD key length in bytes.
    #[must_use]
    pub const fn n_k(self) -> usize {
        self.aead.n_k()
    }

    /// `Nn` — AEAD nonce length in bytes.
    #[must_use]
    pub const fn n_n(self) -> usize {
        self.aead.n_n()
    }

    /// `Nt` — AEAD tag length in bytes.
    #[must_use]
    pub const fn n_t(self) -> usize {
        self.aead.n_t()
    }

    // ── Internal helpers ────────────────────────────────────────────────────────

    #[inline]
    const fn dhkem(self) -> DhKem {
        DhKem::new(self.kem)
    }

    #[inline]
    const fn hpke_kdf(self) -> HpkeKdf {
        match self.kdf {
            KdfId::HkdfSha256 => HpkeKdf::HkdfSha256,
            KdfId::HkdfSha384 => HpkeKdf::HkdfSha384,
            KdfId::HkdfSha512 => HpkeKdf::HkdfSha512,
        }
    }

    #[inline]
    fn suite_id(self) -> Vec<u8> {
        hpke_suite_id(self.kem, self.kdf, self.aead)
    }

    /// Run the key schedule and assemble the shared [`ContextConfig`].
    fn derive_context_config(
        self,
        shared_secret: &[u8],
        info: &[u8],
        psk: &[u8],
        psk_id: &[u8],
        mode: HpkeMode,
    ) -> Result<ContextConfig, CryptoError> {
        let suite_id = self.suite_id();
        let ks = key_schedule(KeyScheduleParams {
            kdf: self.hpke_kdf(),
            suite_id: &suite_id,
            mode,
            shared_secret,
            info,
            psk,
            psk_id,
            nk: self.n_k(),
            nn: self.n_n(),
        })?;
        Ok(ContextConfig {
            aead: HpkeAead::from_id(self.aead),
            kdf: self.hpke_kdf(),
            suite_id,
            key: ks.key,
            base_nonce: ks.base_nonce,
            exporter_secret: ks.exporter_secret,
            nn: self.n_n(),
            nt: self.n_t(),
        })
    }

    /// Build a sender context from a freshly computed shared secret.
    fn build_context_s(
        self,
        shared_secret: &[u8],
        info: &[u8],
        psk: &[u8],
        psk_id: &[u8],
        mode: HpkeMode,
    ) -> Result<HpkeContextS, CryptoError> {
        let config = self.derive_context_config(shared_secret, info, psk, psk_id, mode)?;
        Ok(HpkeContextS::new(config))
    }

    /// Build a recipient context from a freshly computed shared secret.
    fn build_context_r(
        self,
        shared_secret: &[u8],
        info: &[u8],
        psk: &[u8],
        psk_id: &[u8],
        mode: HpkeMode,
    ) -> Result<HpkeContextR, CryptoError> {
        let config = self.derive_context_config(shared_secret, info, psk, psk_id, mode)?;
        Ok(HpkeContextR::new(config))
    }

    // ── Key management ──────────────────────────────────────────────────────────

    /// `DeriveKeyPair(ikm)` — deterministically derive `(sk, serialized_pk)`.
    ///
    /// # Errors
    ///
    /// Propagates KEM errors (e.g. P-256 rejection-sampling exhaustion).
    pub fn derive_key_pair(self, ikm: &[u8]) -> Result<(SecretVec, Vec<u8>), CryptoError> {
        self.dhkem().derive_key_pair(ikm)
    }

    /// `GenerateKeyPair()` — draw `Nsk` random bytes and derive a key pair.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::Rng`] on RNG failure; propagates KEM errors.
    pub fn generate_key_pair<R>(self, rng: &mut R) -> Result<(SecretVec, Vec<u8>), CryptoError>
    where
        R: rand_core::TryCryptoRng + ?Sized,
    {
        let mut ikm = vec![0u8; self.n_sk()];
        rng.try_fill_bytes(&mut ikm).map_err(|_| CryptoError::Rng)?;
        self.derive_key_pair(&ikm)
    }

    /// `SerializePublicKey` — canonical HPKE encoding of a public key.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidKey`] for malformed input.
    pub fn serialize_public_key(self, pk: &[u8]) -> Result<Vec<u8>, CryptoError> {
        self.dhkem().serialize_public_key(pk)
    }

    /// `Serialize`-validate an encapsulated/serialized public key.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidKey`] for malformed input.
    pub fn deserialize_public_key(self, enc: &[u8]) -> Result<Vec<u8>, CryptoError> {
        self.dhkem().deserialize_public_key(enc)
    }

    // ── Mode: Base ──────────────────────────────────────────────────────────────

    /// `SetupBaseS()` derandomized to an explicit `ikm_e` (KAT seam).
    ///
    /// # Errors
    ///
    /// Propagates KEM / key-schedule errors.
    pub(crate) fn setup_base_s_deterministic(
        self,
        pk_r: &[u8],
        info: &[u8],
        ikm_e: &[u8],
    ) -> Result<(Vec<u8>, HpkeContextS), CryptoError> {
        let (shared_secret, enc) = self.dhkem().encap_with_ikm(pk_r, ikm_e)?;
        let ctx = self.build_context_s(shared_secret.as_bytes(), info, b"", b"", HpkeMode::Base)?;
        Ok((enc, ctx))
    }

    /// `SetupBaseS()` — sender setup for mode Base (RFC 9180 §5.1.1).
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::Rng`] on RNG failure; propagates KEM errors.
    pub fn setup_base_s<R>(
        self,
        pk_r: &[u8],
        info: &[u8],
        rng: &mut R,
    ) -> Result<(Vec<u8>, HpkeContextS), CryptoError>
    where
        R: rand_core::TryCryptoRng + ?Sized,
    {
        let mut ikm_e = vec![0u8; self.n_sk()];
        rng.try_fill_bytes(&mut ikm_e)
            .map_err(|_| CryptoError::Rng)?;
        self.setup_base_s_deterministic(pk_r, info, &ikm_e)
    }

    /// `SetupBaseR()` — recipient setup for mode Base.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidKey`] for malformed `enc`; propagates KEM /
    /// key-schedule errors.
    pub fn setup_base_r(
        self,
        enc: &[u8],
        sk_r: &[u8],
        info: &[u8],
    ) -> Result<HpkeContextR, CryptoError> {
        let shared_secret = self.dhkem().decap(enc, sk_r)?;
        self.build_context_r(shared_secret.as_bytes(), info, b"", b"", HpkeMode::Base)
    }

    // ── Mode: PSK ───────────────────────────────────────────────────────────────

    /// `SetupPSKS()` derandomized to an explicit `ikm_e`.
    ///
    /// # Errors
    ///
    /// Propagates KEM / key-schedule errors (including PSK-input validation).
    pub(crate) fn setup_psk_s_deterministic(
        self,
        pk_r: &[u8],
        info: &[u8],
        psk: &[u8],
        psk_id: &[u8],
        ikm_e: &[u8],
    ) -> Result<(Vec<u8>, HpkeContextS), CryptoError> {
        let (shared_secret, enc) = self.dhkem().encap_with_ikm(pk_r, ikm_e)?;
        let ctx =
            self.build_context_s(shared_secret.as_bytes(), info, psk, psk_id, HpkeMode::Psk)?;
        Ok((enc, ctx))
    }

    /// `SetupPSKS()` — sender setup for mode PSK (RFC 9180 §5.1.2).
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::Rng`] on RNG failure, [`CryptoError::BadInput`] for
    /// invalid PSK inputs; propagates KEM errors.
    pub fn setup_psk_s<R>(
        self,
        pk_r: &[u8],
        info: &[u8],
        psk: &[u8],
        psk_id: &[u8],
        rng: &mut R,
    ) -> Result<(Vec<u8>, HpkeContextS), CryptoError>
    where
        R: rand_core::TryCryptoRng + ?Sized,
    {
        let mut ikm_e = vec![0u8; self.n_sk()];
        rng.try_fill_bytes(&mut ikm_e)
            .map_err(|_| CryptoError::Rng)?;
        self.setup_psk_s_deterministic(pk_r, info, psk, psk_id, &ikm_e)
    }

    /// `SetupPSKR()` — recipient setup for mode PSK.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidKey`] / [`CryptoError::BadInput`]; propagates
    /// KEM / key-schedule errors.
    pub fn setup_psk_r(
        self,
        enc: &[u8],
        sk_r: &[u8],
        info: &[u8],
        psk: &[u8],
        psk_id: &[u8],
    ) -> Result<HpkeContextR, CryptoError> {
        let shared_secret = self.dhkem().decap(enc, sk_r)?;
        self.build_context_r(shared_secret.as_bytes(), info, psk, psk_id, HpkeMode::Psk)
    }

    // ── Mode: Auth ──────────────────────────────────────────────────────────────

    /// `SetupAuthS()` derandomized to an explicit `ikm_e`.
    ///
    /// # Errors
    ///
    /// Propagates KEM / key-schedule errors.
    pub(crate) fn setup_auth_s_deterministic(
        self,
        pk_r: &[u8],
        info: &[u8],
        sk_s: &[u8],
        ikm_e: &[u8],
    ) -> Result<(Vec<u8>, HpkeContextS), CryptoError> {
        let (shared_secret, enc) = self.dhkem().auth_encap_with_ikm(pk_r, sk_s, ikm_e)?;
        let ctx = self.build_context_s(shared_secret.as_bytes(), info, b"", b"", HpkeMode::Auth)?;
        Ok((enc, ctx))
    }

    /// `SetupAuthS()` — sender setup for mode Auth (RFC 9180 §5.1.3).
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::Rng`] on RNG failure; propagates KEM errors.
    pub fn setup_auth_s<R>(
        self,
        pk_r: &[u8],
        info: &[u8],
        sk_s: &[u8],
        rng: &mut R,
    ) -> Result<(Vec<u8>, HpkeContextS), CryptoError>
    where
        R: rand_core::TryCryptoRng + ?Sized,
    {
        let mut ikm_e = vec![0u8; self.n_sk()];
        rng.try_fill_bytes(&mut ikm_e)
            .map_err(|_| CryptoError::Rng)?;
        self.setup_auth_s_deterministic(pk_r, info, sk_s, &ikm_e)
    }

    /// `SetupAuthR()` — recipient setup for mode Auth, authenticating `pk_s`.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidKey`]; propagates KEM / key-schedule errors.
    pub fn setup_auth_r(
        self,
        enc: &[u8],
        sk_r: &[u8],
        info: &[u8],
        pk_s: &[u8],
    ) -> Result<HpkeContextR, CryptoError> {
        let shared_secret = self.dhkem().auth_decap(enc, sk_r, pk_s)?;
        self.build_context_r(shared_secret.as_bytes(), info, b"", b"", HpkeMode::Auth)
    }

    // ── Mode: AuthPSK ───────────────────────────────────────────────────────────

    /// `SetupAuthPSKS()` derandomized to an explicit `ikm_e`.
    ///
    /// # Errors
    ///
    /// Propagates KEM / key-schedule errors (including PSK-input validation).
    pub(crate) fn setup_auth_psk_s_deterministic(
        self,
        pk_r: &[u8],
        info: &[u8],
        psk: &[u8],
        psk_id: &[u8],
        sk_s: &[u8],
        ikm_e: &[u8],
    ) -> Result<(Vec<u8>, HpkeContextS), CryptoError> {
        let (shared_secret, enc) = self.dhkem().auth_encap_with_ikm(pk_r, sk_s, ikm_e)?;
        let ctx = self.build_context_s(
            shared_secret.as_bytes(),
            info,
            psk,
            psk_id,
            HpkeMode::AuthPsk,
        )?;
        Ok((enc, ctx))
    }

    /// `SetupAuthPSKS()` — sender setup for mode AuthPSK (RFC 9180 §5.1.4).
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::Rng`] / [`CryptoError::BadInput`]; propagates KEM
    /// errors.
    pub fn setup_auth_psk_s<R>(
        self,
        pk_r: &[u8],
        info: &[u8],
        psk: &[u8],
        psk_id: &[u8],
        sk_s: &[u8],
        rng: &mut R,
    ) -> Result<(Vec<u8>, HpkeContextS), CryptoError>
    where
        R: rand_core::TryCryptoRng + ?Sized,
    {
        let mut ikm_e = vec![0u8; self.n_sk()];
        rng.try_fill_bytes(&mut ikm_e)
            .map_err(|_| CryptoError::Rng)?;
        self.setup_auth_psk_s_deterministic(pk_r, info, psk, psk_id, sk_s, &ikm_e)
    }

    /// `SetupAuthPSKR()` — recipient setup for mode AuthPSK.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidKey`] / [`CryptoError::BadInput`]; propagates
    /// KEM / key-schedule errors.
    pub fn setup_auth_psk_r(
        self,
        enc: &[u8],
        sk_r: &[u8],
        info: &[u8],
        psk: &[u8],
        psk_id: &[u8],
        pk_s: &[u8],
    ) -> Result<HpkeContextR, CryptoError> {
        let shared_secret = self.dhkem().auth_decap(enc, sk_r, pk_s)?;
        self.build_context_r(
            shared_secret.as_bytes(),
            info,
            psk,
            psk_id,
            HpkeMode::AuthPsk,
        )
    }

    // ── Single-shot (RFC 9180 §6.1) ─────────────────────────────────────────────

    /// `SealBase(pkR, info, aad, pt)` — one-shot encryption for mode Base.
    ///
    /// Returns `(enc, ciphertext)`.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::Rng`] on RNG failure,
    /// [`CryptoError::UnsupportedAlgorithm`] for an export-only suite; propagates
    /// KEM / AEAD errors.
    pub fn seal_base<R>(
        self,
        pk_r: &[u8],
        info: &[u8],
        aad: &[u8],
        pt: &[u8],
        rng: &mut R,
    ) -> Result<(Vec<u8>, Vec<u8>), CryptoError>
    where
        R: rand_core::TryCryptoRng + ?Sized,
    {
        let (enc, mut ctx) = self.setup_base_s(pk_r, info, rng)?;
        let ct = ctx.seal(aad, pt)?;
        Ok((enc, ct))
    }

    /// `OpenBase(enc, skR, info, aad, ct)` — one-shot decryption for mode Base.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidKey`] / [`CryptoError::InvalidTag`] /
    /// [`CryptoError::UnsupportedAlgorithm`]; propagates KEM / AEAD errors.
    pub fn open_base(
        self,
        enc: &[u8],
        sk_r: &[u8],
        info: &[u8],
        aad: &[u8],
        ct: &[u8],
    ) -> Result<Vec<u8>, CryptoError> {
        let mut ctx = self.setup_base_r(enc, sk_r, info)?;
        ctx.open(aad, ct)
    }
}