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
//! Document Basic Access key (DBA / BAC).
//!
//! DBA keys are derived from the MRZ document number, date of birth, and
//! date of expiry per ICAO 9303 p11 §9.7.2. The SHA-1 hash of the
//! concatenated MRZ string yields the seed used by BAC (first 16 bytes) or
//! PACE (first 20 bytes).

use chrono::NaiveDate;
use sha1::{Digest, Sha1};
use thiserror::Error;

use crate::crypto::kdf::DeriveKey;
use crate::extension::datetime::DateTimeFormatExt;
use crate::lds::asn1_object_identifiers::{CipherAlgorithm, KeyLength};
use crate::lds::mrz::Mrz;
use crate::proto::access_key::{AccessKey, PACE_REF_KEY_TAG_MRZ};

/// Seed length for BAC (16 bytes).
pub const SEED_LEN_BAC: usize = 16;
/// Seed length for PACE (20 bytes — uncut SHA-1 digest).
pub const SEED_LEN_PACE: usize = 20;

/// Error returned when constructing a [`DBAKey`].
#[derive(Debug, Error)]
pub enum DbaKeyError {
    /// The MRTD number contained a character outside the MRZ alphabet
    /// (`0-9`, `A-Z`, `<`), which would silently corrupt the derived seed.
    #[error("invalid MRZ character {0:?} in document number; only 0-9, A-Z and '<' are allowed")]
    InvalidMrzCharacter(char),
}

/// Returns `true` if every character of `s` is a valid MRZ character
/// (`0-9`, `A-Z`, or `<`) — the alphabet accepted by the ICAO check-digit
/// computation that derives the BAC/PACE seed.
fn is_valid_mrz(s: &str) -> Result<(), DbaKeyError> {
    if let Some(c) = s
        .chars()
        .find(|c| !(c.is_ascii_digit() || c.is_ascii_uppercase() || *c == '<'))
    {
        return Err(DbaKeyError::InvalidMrzCharacter(c));
    }
    Ok(())
}

/// Document Basic Access key.
#[derive(Debug, Clone)]
pub struct DBAKey {
    mrtd_number: String,
    /// Original date of birth, stored verbatim so the getter round-trips the
    /// input exactly (the MRZ `YYMMDD` form loses the century).
    dob: NaiveDate,
    /// Original date of expiry (see [`DBAKey::dob`]).
    doe: NaiveDate,
    seed_len: usize,
}

impl DBAKey {
    /// Constructs a [`DBAKey`] from the MRTD number and birth/expiry dates.
    ///
    /// If `pace_mode` is `true`, the seed length is set to 20 bytes (uncut
    /// SHA-1 digest); otherwise it is 16 bytes (BAC).
    ///
    /// # Errors
    /// Returns [`DbaKeyError::InvalidMrzCharacter`] if `mrtd_number` contains a
    /// character outside the MRZ alphabet (`0-9`, `A-Z`, `<`). The
    /// `date_of_birth` / `date_of_expiry` inputs are typed [`NaiveDate`]s and
    /// always format to MRZ-valid `YYMMDD` digits, so they cannot be invalid.
    pub fn new(
        mrtd_number: impl Into<String>,
        date_of_birth: NaiveDate,
        date_of_expiry: NaiveDate,
        pace_mode: bool,
    ) -> Result<Self, DbaKeyError> {
        let mrtd_number = mrtd_number.into();
        is_valid_mrz(&mrtd_number)?;
        Ok(Self {
            mrtd_number,
            dob: date_of_birth,
            doe: date_of_expiry,
            seed_len: if pace_mode {
                SEED_LEN_PACE
            } else {
                SEED_LEN_BAC
            },
        })
    }

    /// Constructs a [`DBAKey`] from a parsed [`Mrz`] (BAC mode).
    ///
    /// # Errors
    /// Returns [`DbaKeyError::InvalidMrzCharacter`] if the MRZ document number
    /// contains a character outside the MRZ alphabet. (A document number parsed
    /// from a valid MRZ is always within the alphabet.)
    pub fn from_mrz(mrz: &Mrz) -> Result<Self, DbaKeyError> {
        Self::new(
            mrz.document_number(),
            mrz.date_of_birth,
            mrz.date_of_expiry,
            false,
        )
    }

    /// Returns `K_seed` (truncated to `seed_len` bytes) as specified in
    /// Appendix D.2 of ICAO 9303 Part 11.
    pub fn key_seed(&self) -> Vec<u8> {
        let padded_mrtd = pad_right(&self.mrtd_number, 9, '<');
        let dob = self.dob.format_yymmdd();
        let doe = self.doe.format_yymmdd();
        // The seed inputs are guaranteed to use the MRZ alphabet: `new`/`from_mrz`
        // validate the document number, '<'-padding is itself valid, and the
        // YYMMDD dates are formatted from typed `NaiveDate`s (always digits). The
        // check-digit computation therefore never returns `None` here.
        let cdn = Mrz::calculate_check_digit(&padded_mrtd).unwrap_or(0);
        let cdb = Mrz::calculate_check_digit(&dob).unwrap_or(0);
        let cde = Mrz::calculate_check_digit(&doe).unwrap_or(0);
        let kmrz = format!(
            "{padded_mrtd}{cdn}{dob}{cdb}{doe}{cde}",
            padded_mrtd = padded_mrtd,
            cdn = cdn,
            dob = dob,
            cdb = cdb,
            doe = doe,
            cde = cde,
        );
        let mut hasher = Sha1::new();
        hasher.update(kmrz.as_bytes());
        let digest = hasher.finalize();
        digest[..self.seed_len].to_vec()
    }

    /// Returns `K_enc` (3DES encryption key for BAC / PACE).
    pub fn enc_key(&self) -> Vec<u8> {
        DeriveKey::des_ede(&self.key_seed(), false)
    }

    /// Returns `K_mac` (ISO 9797 MAC algorithm 3 key).
    pub fn mac_key(&self) -> Vec<u8> {
        DeriveKey::iso9797_mac_alg3(&self.key_seed())
    }

    /// Returns the MRTD number used to build the seed.
    pub fn mrtd_number(&self) -> &str {
        &self.mrtd_number
    }

    /// Returns the date of birth exactly as supplied to [`DBAKey::new`].
    pub fn date_of_birth(&self) -> NaiveDate {
        self.dob
    }

    /// Returns the date of expiry exactly as supplied to [`DBAKey::new`].
    pub fn date_of_expiry(&self) -> NaiveDate {
        self.doe
    }

    /// Returns `true` when the key was constructed with the PACE seed length.
    pub fn is_pace_mode(&self) -> bool {
        self.seed_len == SEED_LEN_PACE
    }
}

impl AccessKey for DBAKey {
    fn pace_ref_key_tag(&self) -> u8 {
        PACE_REF_KEY_TAG_MRZ
    }

    fn kpi(
        &self,
        cipher_algorithm: CipherAlgorithm,
        key_length: KeyLength,
    ) -> Result<Vec<u8>, String> {
        let seed = self.key_seed();
        match (cipher_algorithm, key_length) {
            (CipherAlgorithm::DeSede, _) => Ok(DeriveKey::des_ede(&seed, true)),
            (CipherAlgorithm::Aes, KeyLength::S128) => Ok(DeriveKey::aes128(&seed, true)),
            (CipherAlgorithm::Aes, KeyLength::S192) => Ok(DeriveKey::aes192(&seed, true)),
            (CipherAlgorithm::Aes, KeyLength::S256) => Ok(DeriveKey::aes256(&seed, true)),
        }
    }
}

fn pad_right(s: &str, min_len: usize, fill: char) -> String {
    if s.len() >= min_len {
        s.to_string()
    } else {
        let mut out = s.to_string();
        out.extend(std::iter::repeat_n(fill, min_len - s.len()));
        out
    }
}

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

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

    /// ICAO 9303 p11 Appendix D.2 worked example:
    ///   documentNumber = "L898902C<"      (padded to 9 chars with '<')
    ///   dateOfBirth    = "690806"         → 6 Aug 1969
    ///   dateOfExpiry   = "940623"         → 23 Jun 1994
    ///   K_seed (BAC, 16 bytes) = 239AB9CB282DAF66231DC5A4DF6BFBAE
    #[test]
    fn key_seed_matches_icao_worked_example() {
        let key = DBAKey::new(
            "L898902C",
            NaiveDate::from_ymd_opt(1969, 8, 6).unwrap(),
            NaiveDate::from_ymd_opt(1994, 6, 23).unwrap(),
            false,
        )
        .unwrap();
        let seed = key.key_seed();
        assert_eq!(hex::encode_upper(&seed), "239AB9CB282DAF66231DC5A4DF6BFBAE");
    }

    #[test]
    fn pace_mode_seed_is_20_bytes() {
        let key = DBAKey::new(
            "L898902C",
            NaiveDate::from_ymd_opt(1969, 8, 6).unwrap(),
            NaiveDate::from_ymd_opt(1994, 6, 23).unwrap(),
            true,
        )
        .unwrap();
        assert_eq!(key.key_seed().len(), 20);
        assert!(key.is_pace_mode());
    }

    #[test]
    fn bac_mode_seed_is_16_bytes() {
        let key = DBAKey::new(
            "L898902C",
            NaiveDate::from_ymd_opt(1969, 8, 6).unwrap(),
            NaiveDate::from_ymd_opt(1994, 6, 23).unwrap(),
            false,
        )
        .unwrap();
        assert_eq!(key.key_seed().len(), 16);
        assert!(!key.is_pace_mode());
    }

    #[test]
    fn pace_ref_key_tag_is_mrz() {
        let key = DBAKey::new(
            "X",
            NaiveDate::from_ymd_opt(2000, 1, 1).unwrap(),
            NaiveDate::from_ymd_opt(2010, 1, 1).unwrap(),
            false,
        )
        .unwrap();
        assert_eq!(key.pace_ref_key_tag(), PACE_REF_KEY_TAG_MRZ);
    }

    #[test]
    fn kpi_desede_returns_16_bytes() {
        let key = DBAKey::new(
            "L898902C",
            NaiveDate::from_ymd_opt(1969, 8, 6).unwrap(),
            NaiveDate::from_ymd_opt(1994, 6, 23).unwrap(),
            true,
        )
        .unwrap();
        let kpi = key.kpi(CipherAlgorithm::DeSede, KeyLength::S128).unwrap();
        // DeriveKey::des_ede produces a 16-byte 3DES key.
        assert_eq!(kpi.len(), 16);
    }

    #[test]
    fn kpi_aes_key_lengths() {
        let key = DBAKey::new(
            "L898902C",
            NaiveDate::from_ymd_opt(1969, 8, 6).unwrap(),
            NaiveDate::from_ymd_opt(1994, 6, 23).unwrap(),
            true,
        )
        .unwrap();
        assert_eq!(
            key.kpi(CipherAlgorithm::Aes, KeyLength::S128)
                .unwrap()
                .len(),
            16
        );
        assert_eq!(
            key.kpi(CipherAlgorithm::Aes, KeyLength::S192)
                .unwrap()
                .len(),
            24
        );
        assert_eq!(
            key.kpi(CipherAlgorithm::Aes, KeyLength::S256)
                .unwrap()
                .len(),
            32
        );
    }

    #[test]
    fn enc_and_mac_key_lengths() {
        let key = DBAKey::new(
            "L898902C",
            NaiveDate::from_ymd_opt(1969, 8, 6).unwrap(),
            NaiveDate::from_ymd_opt(1994, 6, 23).unwrap(),
            false,
        )
        .unwrap();
        // 3DES key (K_enc) and MAC key are each 16 bytes per ICAO 9303.
        assert_eq!(key.enc_key().len(), 16);
        assert_eq!(key.mac_key().len(), 16);
    }

    #[test]
    fn date_getters_round_trip_input_century() {
        // Dates whose century the YYMMDD pivot heuristic could get wrong must
        // still be reported exactly as supplied to `new`.
        let dob = NaiveDate::from_ymd_opt(2005, 3, 9).unwrap();
        let doe = NaiveDate::from_ymd_opt(2045, 12, 31).unwrap();
        let key = DBAKey::new("D23145890", dob, doe, false).unwrap();
        assert_eq!(key.date_of_birth(), dob);
        assert_eq!(key.date_of_expiry(), doe);
    }

    #[test]
    fn from_mrz_uses_td3_fields() {
        let mrz = Mrz::from_bytes(
            "P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<L898902C36UTO7408122F1204159ZE184226B<<<<<10".as_bytes().to_vec(),
        )
        .unwrap();
        let key = DBAKey::from_mrz(&mrz).unwrap();
        assert_eq!(key.mrtd_number(), "L898902C3");
        assert_eq!(
            key.date_of_birth(),
            NaiveDate::from_ymd_opt(1974, 8, 12).unwrap()
        );
        assert_eq!(
            key.date_of_expiry(),
            NaiveDate::from_ymd_opt(2012, 4, 15).unwrap()
        );
        assert!(!key.is_pace_mode());
    }

    /// PACE worked example: doc number `T22000129`, DOB 1964-08-12, DOE
    /// 2010-10-31 — `K_seed`, `K_enc`, `K_mac`, and `K_π` for AES-128.
    #[test]
    fn pace_mode_worked_example_derives_expected_keys() {
        let key = DBAKey::new(
            "T22000129",
            NaiveDate::from_ymd_opt(1964, 8, 12).unwrap(),
            NaiveDate::from_ymd_opt(2010, 10, 31).unwrap(),
            true,
        )
        .unwrap();
        assert_eq!(
            hex::encode(key.key_seed()),
            "7e2d2a41c74ea0b38cd36f863939bfa8e9032aad"
        );
        assert_eq!(
            hex::encode(key.enc_key()),
            "3dc4f8862f8a1570b57fefdcfec43e46"
        );
        assert_eq!(
            hex::encode(key.mac_key()),
            "bc641c6b2fa8b5704552322007761f85"
        );
        assert_eq!(
            hex::encode(key.kpi(CipherAlgorithm::Aes, KeyLength::S128).unwrap()),
            "89ded1b26624ec1e634c1989302849dd"
        );
    }

    /// BAC seed for the Appendix D TD2 Stevenson MRZ (extended document
    /// number `D23145890734`, DOB 1934-07-12, DOE 1995-07-12):
    /// `b366ad85…14730`.
    #[test]
    fn bac_seed_for_stevenson_td2_extended() {
        let key = DBAKey::new(
            "D23145890734",
            NaiveDate::from_ymd_opt(1934, 7, 12).unwrap(),
            NaiveDate::from_ymd_opt(1995, 7, 12).unwrap(),
            false,
        )
        .unwrap();
        assert_eq!(
            hex::encode(key.key_seed()),
            "b366ad857ddca2b08c0e299811714730"
        );
    }

    /// Same extended document number via the MRZ helper `DBAKey::from_mrz`.
    #[test]
    fn bac_seed_for_stevenson_td2_from_mrz() {
        let mrz = Mrz::from_bytes(
            "I<UTOSTEVENSON<<PETER<JOHN<<<<<<<<<<D23145890<UTO3407127M95071227349<<<8"
                .as_bytes()
                .to_vec(),
        )
        .unwrap();
        let key = DBAKey::from_mrz(&mrz).unwrap();
        assert_eq!(
            hex::encode(key.key_seed()),
            "b366ad857ddca2b08c0e299811714730"
        );
    }

    #[test]
    fn new_rejects_invalid_mrz_character_in_document_number() {
        // Lowercase letters and spaces are outside the MRZ alphabet and would
        // silently corrupt the derived seed, so construction must fail.
        let dob = NaiveDate::from_ymd_opt(1969, 8, 6).unwrap();
        let doe = NaiveDate::from_ymd_opt(1994, 6, 23).unwrap();

        assert!(matches!(
            DBAKey::new("L898902c", dob, doe, false),
            Err(DbaKeyError::InvalidMrzCharacter('c'))
        ));
        assert!(matches!(
            DBAKey::new("L89 902C", dob, doe, false),
            Err(DbaKeyError::InvalidMrzCharacter(' '))
        ));
    }

    #[test]
    fn new_accepts_valid_mrz_document_number() {
        // All-uppercase / digit / '<' document numbers are accepted.
        let dob = NaiveDate::from_ymd_opt(1969, 8, 6).unwrap();
        let doe = NaiveDate::from_ymd_opt(1994, 6, 23).unwrap();
        assert!(DBAKey::new("L898902C<", dob, doe, false).is_ok());
        assert!(DBAKey::new("D23145890734", dob, doe, true).is_ok());
    }
}