dmrtd 0.3.2

eMRTD / ICAO 9303 reader core in pure Rust — BAC, PACE (ECDH-GM P-256), MRZ, LDS parsing, secure messaging. Transport-agnostic (NFC plugs in via a Transceiver trait).
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! PKCS#3 Diffie-Hellman engine.
//!
//! Implements the key-exchange primitives used by PACE:
//! - [`DhParameterSpec`] — group parameters `(p, g, length)`.
//! - [`DhKeyPair`] — `(public_key, private_key)` pair.
//! - [`DHpkcs3Engine`] — engine for generating key pairs, computing shared
//!   secrets, and deriving the ephemeral generator for PACE-GM.
//!
//! Arithmetic uses [`num_bigint::BigUint`] since DH operates on non-negative
//! integers modulo a prime `p`. Random private keys are drawn uniformly from
//! `[1, q-1]` when the subgroup order `q` is known, otherwise from a
//! `length`-bit range capped at `p-1`.

use num_bigint::BigUint;
use num_traits::{One, Zero};
use rand::rand_core::UnwrapErr;
use rand::{rngs::StdRng, rngs::SysRng, Rng, SeedableRng};
use thiserror::Error;

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Error returned by [`DHpkcs3Engine`] operations.
#[derive(Debug, Error)]
#[error("DHpkcs3EngineError: {0}")]
pub(crate) struct DhPkcs3EngineError(pub String);

// ---------------------------------------------------------------------------
// DhParameterSpec
// ---------------------------------------------------------------------------

/// Diffie-Hellman group parameters.
#[derive(Debug, Clone)]
pub(crate) struct DhParameterSpec {
    p: BigUint,
    g: BigUint,
    length: u32,
    /// Order `q` of the prime-order subgroup generated by `g`, when known.
    /// When set, private keys are drawn uniformly from `[1, q-1]`, which avoids
    /// the modulo-bias that results from sampling a full `length`-bit value
    /// (since `q < 2^length`).
    q: Option<BigUint>,
}

impl DhParameterSpec {
    /// Creates a new [`DhParameterSpec`] with the given prime `p`, generator
    /// `g`, and private-key bit `length`.
    pub fn new(p: BigUint, g: BigUint, length: u32) -> Self {
        Self {
            p,
            g,
            length,
            q: None,
        }
    }

    /// Attaches the prime-order subgroup order `q`, enabling unbiased private
    /// key generation in `[1, q-1]`.
    pub fn with_subgroup_order(mut self, q: BigUint) -> Self {
        self.q = Some(q);
        self
    }

    /// Order of the prime-order subgroup, if known.
    pub fn q(&self) -> Option<&BigUint> {
        self.q.as_ref()
    }

    /// Private-key bit length.
    pub fn length(&self) -> u32 {
        self.length
    }

    /// Generator `g`.
    pub fn g(&self) -> &BigUint {
        &self.g
    }

    /// Prime modulus `p`.
    pub fn p(&self) -> &BigUint {
        &self.p
    }
}

impl std::fmt::Display for DhParameterSpec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "DhParameterSpec; p: {:?}, g: {:?}, length: {}",
            self.p.to_bytes_be(),
            self.g.to_bytes_be(),
            self.length,
        )
    }
}

// ---------------------------------------------------------------------------
// DHpkcs3Engine
// ---------------------------------------------------------------------------

/// PKCS#3 Diffie-Hellman engine. Holds a [`DhParameterSpec`] and a key pair;
/// derives shared secrets and the PACE-GM ephemeral generator.
#[derive(Debug, Clone)]
pub(crate) struct DHpkcs3Engine {
    parameter_spec: DhParameterSpec,
    public_key: BigUint,
    private_key: BigUint,
}

impl DHpkcs3Engine {
    /// Constructs an engine from a fixed `private_key`.
    ///
    /// Test-only convenience over [`DHpkcs3Engine::new`]; production callers
    /// always let the engine generate the key pair.
    #[cfg(test)]
    pub fn from_private(
        private_key: BigUint,
        parameter_spec: DhParameterSpec,
    ) -> Result<Self, DhPkcs3EngineError> {
        Self::new(parameter_spec, Some(private_key), None)
    }

    /// Constructs an engine; if `private_key` is `None`, a new key pair is
    /// generated (optionally deterministic given `seed`).
    pub fn new(
        parameter_spec: DhParameterSpec,
        private_key: Option<BigUint>,
        seed: Option<u64>,
    ) -> Result<Self, DhPkcs3EngineError> {
        let priv_key = match private_key {
            Some(p) => p,
            None => Self::generate_private_key(&parameter_spec, seed)?,
        };
        // Reject degenerate / out-of-range private keys. A zero key yields a
        // trivial public key; a key >= the (sub)group order is outside the
        // valid private-key range.
        if priv_key.is_zero() {
            return Err(DhPkcs3EngineError(
                "Private key must not be zero".to_string(),
            ));
        }
        // Valid range is [1, q-1] when the subgroup order q is known, else
        // [1, p-2]: p is the modulus, not the group order, so the exclusive
        // upper bound for the no-q case is p-1 (x = p-1 yields a degenerate key).
        let group_order;
        let upper: &BigUint = match parameter_spec.q() {
            Some(q) => q,
            None => {
                group_order = parameter_spec.p() - BigUint::one();
                &group_order
            }
        };
        if &priv_key >= upper {
            return Err(DhPkcs3EngineError(format!(
                "Private key must be less than the {} order",
                if parameter_spec.q().is_some() {
                    "subgroup"
                } else {
                    "group"
                }
            )));
        }
        let pub_key = Self::generate_public_key(&priv_key, &parameter_spec);
        Ok(Self {
            parameter_spec,
            public_key: pub_key,
            private_key: priv_key,
        })
    }

    /// Public key.
    pub fn public_key(&self) -> &BigUint {
        &self.public_key
    }

    /// Private key. Test-only accessor; production code never reads the private
    /// key back out of the engine.
    #[cfg(test)]
    pub fn private_key(&self) -> &BigUint {
        &self.private_key
    }

    /// Validates a peer's DH public key before it is used in an exponentiation.
    ///
    /// Rejects out-of-range values (`y < 2` or `y > p-2`, which covers the
    /// degenerate `0`, `1`, and `p-1` keys) and, when the subgroup order `q` is
    /// known, performs the small-subgroup confinement check `y^q mod p == 1`.
    /// This prevents small-subgroup / invalid-key attacks against PACE-DH.
    fn validate_peer_public_key(&self, y: &BigUint) -> Result<(), DhPkcs3EngineError> {
        let p = self.parameter_spec.p();
        let two = BigUint::from(2u32);
        // p must be large enough for a meaningful range; guards the `p - 2`.
        if p < &two {
            return Err(DhPkcs3EngineError(
                "Invalid DH modulus p (must be >= 2)".to_string(),
            ));
        }
        let upper = p - &two; // p - 2
        if y < &two || y > &upper {
            return Err(DhPkcs3EngineError(
                "Peer DH public key out of range; require 2 <= y <= p-2".to_string(),
            ));
        }
        if let Some(q) = self.parameter_spec.q() {
            if y.modpow(q, p) != BigUint::one() {
                return Err(DhPkcs3EngineError(
                    "Peer DH public key fails small-subgroup check (y^q mod p != 1)".to_string(),
                ));
            }
        }
        Ok(())
    }

    /// Computes the shared secret `otherPublicKey^privateKey mod p`.
    ///
    /// The peer public key is validated first (range + small-subgroup check);
    /// see [`validate_peer_public_key`](Self::validate_peer_public_key).
    pub fn compute_secret_key(
        &self,
        other_public_key: &BigUint,
    ) -> Result<BigUint, DhPkcs3EngineError> {
        self.validate_peer_public_key(other_public_key)?;
        Ok(other_public_key.modpow(&self.private_key, self.parameter_spec.p()))
    }

    /// Computes the PACE-GM ephemeral generator:
    /// `G_ephemeral = (g^nonce mod p * H) mod p` where `H` is the shared
    /// secret derived from `other_public_key`.
    pub fn compute_generator(
        &self,
        other_public_key: &BigUint,
        nonce: &BigUint,
    ) -> Result<BigUint, DhPkcs3EngineError> {
        let h = self.compute_secret_key(other_public_key)?;
        let g_exp = self
            .parameter_spec
            .g()
            .modpow(nonce, self.parameter_spec.p());
        let g_prime = (g_exp * h) % self.parameter_spec.p();
        // A valid generator must lie in [2, p-2]: 0 and 1 have trivial order,
        // and p-1 is the order-2 element — all degenerate for the ephemeral DH
        // exchange.
        let p = self.parameter_spec.p();
        let two = BigUint::from(2u32);
        if g_prime < two || g_prime > p - &two {
            return Err(DhPkcs3EngineError(
                "Mapped generator is degenerate (outside [2, p-2])".to_string(),
            ));
        }
        Ok(g_prime)
    }

    // -----------------------------------------------------------------------
    // Internal helpers
    // -----------------------------------------------------------------------

    fn generate_private_key(
        spec: &DhParameterSpec,
        seed: Option<u64>,
    ) -> Result<BigUint, DhPkcs3EngineError> {
        // When the subgroup order `q` is known, draw x uniformly from [1, q-1]
        // — the correct, unbiased range for a DH private key. Falling back to a
        // raw `length`-bit draw (when q is absent) is biased because q < 2^len.
        if let Some(q) = spec.q() {
            // Guard against a degenerate subgroup order: with q <= 1 the range
            // [1, q-1] is empty and the rejection-sampling loop would never
            // terminate.
            if q <= &BigUint::one() {
                return Err(DhPkcs3EngineError(format!(
                    "Invalid subgroup order q - must be greater than 1, got {q}"
                )));
            }
            let keep_bits = q.bits();
            let byte_len = (keep_bits as usize).div_ceil(8);
            let upper = q.clone();
            let lower = BigUint::one();
            let mut bytes = vec![0u8; byte_len.max(1)];
            return Ok(match seed {
                Some(s) => Self::draw_in_range(
                    &mut StdRng::seed_from_u64(s),
                    &mut bytes,
                    &lower,
                    &upper,
                    keep_bits,
                ),
                None => Self::draw_in_range(
                    &mut UnwrapErr(SysRng),
                    &mut bytes,
                    &lower,
                    &upper,
                    keep_bits,
                ),
            });
        }

        let length = spec.length;
        if length == 0 || !length.is_multiple_of(8) {
            return Err(DhPkcs3EngineError(format!(
                "Invalid bitLength value - {length}"
            )));
        }
        let byte_len = (length / 8) as usize;
        let lower = BigUint::one() << (length - 1);
        // Cap the draw at p-1 so a generated key is always a valid private key
        // (< the group order); `new` would otherwise reject an in-range-but-
        // >= p-1 draw. For real parameters (length << p.bits()) 2^length < p-1,
        // so this is a no-op and the distribution is unchanged.
        let upper = (BigUint::one() << length).min(spec.p() - BigUint::one());
        // If the cap collapsed the range (p too small for this `length`), there
        // is no valid value to draw — fail instead of looping forever.
        if upper <= lower {
            return Err(DhPkcs3EngineError(format!(
                "No valid private-key range: 2^(length-1) ({lower}) >= min(2^length, p-1) ({upper})"
            )));
        }
        let mut bytes = vec![0u8; byte_len];
        // The buffer is exactly `length` bits wide, so no high bits to mask;
        // the [2^(length-1), 2^length) check selects the top-bit-set half.
        let keep_bits = length as u64;

        match seed {
            Some(s) => {
                let mut rng = StdRng::seed_from_u64(s);
                Ok(Self::draw_in_range(
                    &mut rng, &mut bytes, &lower, &upper, keep_bits,
                ))
            }
            None => {
                let mut rng = UnwrapErr(SysRng);
                Ok(Self::draw_in_range(
                    &mut rng, &mut bytes, &lower, &upper, keep_bits,
                ))
            }
        }
    }

    /// Rejection-samples a value in the half-open range `[lower, upper)`.
    ///
    /// `keep_bits` is the number of significant bits to retain from the drawn
    /// buffer: the high bits of the leading byte beyond `keep_bits` are masked
    /// off so each candidate already fits in `[0, 2^keep_bits)`. Choosing
    /// `keep_bits = upper.bits()` keeps the rejection probability below 50% per
    /// iteration regardless of where `upper` sits relative to a byte boundary.
    fn draw_in_range<R: Rng>(
        rng: &mut R,
        buf: &mut [u8],
        lower: &BigUint,
        upper: &BigUint,
        keep_bits: u64,
    ) -> BigUint {
        let excess = (buf.len() as u64 * 8).saturating_sub(keep_bits);
        loop {
            rng.fill_bytes(buf);
            // Drop the surplus high bits of the leading byte (excess is 0..=7
            // for a tightly-sized buffer) so candidates stay in [0, 2^keep_bits).
            if excess > 0 {
                if let Some(first) = buf.first_mut() {
                    *first &= 0xFFu8 >> excess;
                }
            }
            let n = BigUint::from_bytes_be(buf);
            if &n >= lower && &n < upper {
                return n;
            }
        }
    }

    fn generate_public_key(private_key: &BigUint, spec: &DhParameterSpec) -> BigUint {
        spec.g().modpow(private_key, spec.p())
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // Small test group: p = 23, g = 5. All values fit in a byte.
    // length=8 bits so private keys are drawn from [128, 256), but since p=23
    // these are reduced modulo p. This is *not* a secure group — just numeric
    // sanity.
    fn small_spec() -> DhParameterSpec {
        DhParameterSpec::new(BigUint::from(23u32), BigUint::from(5u32), 8)
    }

    #[test]
    fn key_pair_roundtrip_with_fixed_private() {
        let spec = small_spec();
        let engine = DHpkcs3Engine::from_private(BigUint::from(6u32), spec.clone()).unwrap();
        // 5^6 mod 23 = 15625 mod 23 = 8
        assert_eq!(engine.public_key(), &BigUint::from(8u32));
        assert_eq!(engine.private_key(), &BigUint::from(6u32));
    }

    #[test]
    fn shared_secret_symmetric() {
        let spec = small_spec();
        let alice = DHpkcs3Engine::from_private(BigUint::from(6u32), spec.clone()).unwrap();
        let bob = DHpkcs3Engine::from_private(BigUint::from(15u32), spec).unwrap();

        let s_ab = alice.compute_secret_key(bob.public_key()).unwrap();
        let s_ba = bob.compute_secret_key(alice.public_key()).unwrap();
        assert_eq!(s_ab, s_ba);
    }

    #[test]
    fn compute_generator_matches_definition() {
        let spec = small_spec();
        let nonce = BigUint::from(3u32);

        let alice = DHpkcs3Engine::from_private(BigUint::from(6u32), spec.clone()).unwrap();
        let bob = DHpkcs3Engine::from_private(BigUint::from(15u32), spec.clone()).unwrap();

        let h = alice.compute_secret_key(bob.public_key()).unwrap();
        let g_exp = spec.g().modpow(&nonce, spec.p());
        let expected = (&g_exp * &h) % spec.p();

        let got = alice.compute_generator(bob.public_key(), &nonce).unwrap();
        assert_eq!(got, expected);
    }

    #[test]
    fn seeded_private_key_is_deterministic() {
        // A subgroup order keeps generated keys in [1, q-1] (q < p), so they
        // pass the private-key range validation in `new`.
        let spec = DhParameterSpec::new(BigUint::from(23u32), BigUint::from(5u32), 8)
            .with_subgroup_order(BigUint::from(11u32));
        let a = DHpkcs3Engine::new(spec.clone(), None, Some(42)).unwrap();
        let b = DHpkcs3Engine::new(spec, None, Some(42)).unwrap();
        assert_eq!(a.private_key(), b.private_key());
        assert_eq!(a.public_key(), b.public_key());
    }

    #[test]
    fn compute_secret_key_rejects_out_of_range_peer() {
        // p = 23, no q → only the 2 <= y <= p-2 range check applies.
        let spec = small_spec();
        let engine = DHpkcs3Engine::from_private(BigUint::from(6u32), spec).unwrap();
        // Degenerate / out-of-range peers: 0, 1, p-1.
        assert!(engine.compute_secret_key(&BigUint::zero()).is_err());
        assert!(engine.compute_secret_key(&BigUint::one()).is_err());
        assert!(engine.compute_secret_key(&BigUint::from(22u32)).is_err()); // p-1
                                                                            // In-range peer succeeds.
        assert!(engine.compute_secret_key(&BigUint::from(8u32)).is_ok());
    }

    #[test]
    fn compute_secret_key_rejects_small_subgroup_peer() {
        // p = 467, p-1 = 2 * 233. The order-233 subgroup is the quadratic
        // residues; g = 4 (= 2^2) generates it, q = 233.
        let spec = DhParameterSpec::new(BigUint::from(467u32), BigUint::from(4u32), 8)
            .with_subgroup_order(BigUint::from(233u32));
        let engine = DHpkcs3Engine::from_private(BigUint::from(5u32), spec).unwrap();

        // 4 is a quadratic residue → 4^233 mod 467 == 1 → accepted.
        assert!(engine.compute_secret_key(&BigUint::from(4u32)).is_ok());
        // 2 is a non-residue (467 ≡ 3 mod 8) → 2^233 mod 467 == -1 → rejected.
        let err = engine.compute_secret_key(&BigUint::from(2u32)).unwrap_err();
        assert!(err.0.contains("small-subgroup"));
    }

    #[test]
    fn zero_private_key_is_rejected() {
        let spec = small_spec();
        let err = DHpkcs3Engine::from_private(BigUint::zero(), spec).unwrap_err();
        assert!(err.0.contains("must not be zero"));
    }

    #[test]
    fn out_of_range_private_key_is_rejected() {
        // p = 23, no subgroup order → private key must be < p.
        let spec = small_spec();
        let err = DHpkcs3Engine::from_private(BigUint::from(23u32), spec).unwrap_err();
        assert!(err.0.contains("less than"));
    }

    #[test]
    fn degenerate_subgroup_order_is_rejected() {
        // q = 1 would make the sampling range [1, 0) empty; the engine must
        // error instead of looping forever.
        let spec = DhParameterSpec::new(BigUint::from(23u32), BigUint::from(5u32), 8)
            .with_subgroup_order(BigUint::one());
        let err = DHpkcs3Engine::new(spec, None, Some(0)).unwrap_err();
        assert!(err.0.contains("subgroup order"));
    }

    #[test]
    fn private_key_respects_subgroup_order_q() {
        // With q set, generated private keys must land in [1, q-1] regardless
        // of `length`, eliminating the modulo bias of a raw length-bit draw.
        let q = BigUint::from(101u32);
        let spec = DhParameterSpec::new(BigUint::from(7919u32), BigUint::from(7u32), 256)
            .with_subgroup_order(q.clone());
        for seed in 0..50u64 {
            let engine = DHpkcs3Engine::new(spec.clone(), None, Some(seed)).unwrap();
            let x = engine.private_key();
            assert!(*x >= BigUint::one(), "x must be >= 1");
            assert!(*x < q, "x ({x}) must be < q ({q})");
        }
    }

    #[test]
    fn generated_private_key_is_within_range() {
        // Use length=16 so range is [2^15, 2^16) = [32768, 65536).
        let spec = DhParameterSpec::new(BigUint::from(2147483647u32), BigUint::from(5u32), 16);
        let engine = DHpkcs3Engine::new(spec, None, Some(1)).unwrap();
        let lower = BigUint::one() << 15;
        let upper = BigUint::one() << 16;
        assert!(engine.private_key() >= &lower);
        assert!(engine.private_key() < &upper);
    }

    #[test]
    fn non_multiple_of_8_bit_length_is_rejected() {
        let spec = DhParameterSpec::new(BigUint::from(23u32), BigUint::from(5u32), 7);
        let err = DHpkcs3Engine::new(spec, None, Some(0)).unwrap_err();
        assert!(err.0.contains("Invalid bitLength"));
    }

    #[test]
    fn zero_bit_length_is_rejected() {
        let spec = DhParameterSpec::new(BigUint::from(23u32), BigUint::from(5u32), 0);
        let err = DHpkcs3Engine::new(spec, None, Some(0)).unwrap_err();
        assert!(err.0.contains("Invalid bitLength"));
    }

    #[test]
    fn empty_range_after_cap_is_rejected() {
        // p too small for `length`: lower = 2^15 = 32768, but min(2^16, p-1)=22,
        // so the range is empty — must error rather than loop forever.
        let spec = DhParameterSpec::new(BigUint::from(23u32), BigUint::from(5u32), 16);
        let err = DHpkcs3Engine::new(spec, None, Some(0)).unwrap_err();
        assert!(err.0.contains("No valid private-key range"));
    }
}