dayzmake-core 0.2.1

Readers and writers for DayZ file formats: PBO, rapified config, P3D, PAA, BI keys and signatures
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
//! Functions for creating and working with BI keys and signatures

use std::fmt::Write as _;
use std::io::{Error, Read, Write};
use std::path::{Path, PathBuf};

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use getrandom::SysRng;
use rsa::hazmat::{rsa_decrypt_and_check, rsa_encrypt};
use rsa::rand_core::TryCryptoRng;
use rsa::traits::{PrivateKeyParts, PublicKeyParts};
use rsa::{BoxedUint, PrivateKey, PublicKey};
use sha1::{Digest, Sha1};
use zeroize::Zeroizing;

use crate::error::{ErrorExt, printable};
use crate::io::{ReadExt, WriteExt};
use crate::pbo::PBO;

/// BI private key (.biprivatekey)
pub struct BIPrivateKey {
    name: String,
    length: u32,
    exponent: u32,
    /// The validated key: `n`, `e`, `d`, `p`, `q` and the CRT values, checked against each other on creation.
    key: PrivateKey,
}

/// BI public key (.bikey)
#[derive(Debug)]
pub struct BIPublicKey {
    name: String,
    length: u32,
    exponent: u32,
    key: PublicKey,
}

/// BI signature version
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BISignVersion {
    /// Version 2
    V2,
    /// Version 3
    V3,
}

/// BI signature (.bisign)
#[derive(Debug)]
pub struct BISign {
    version: BISignVersion,
    name: String,
    length: u32,
    exponent: u32,
    n: BoxedUint,
    sig1: BoxedUint,
    sig2: BoxedUint,
    sig3: BoxedUint,
}

impl std::fmt::Debug for BIPrivateKey {
    /// Prints the name and length only, never any key material.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BIPrivateKey")
            .field("name", &self.name)
            .field("length", &self.length)
            .finish_non_exhaustive()
    }
}

/// Writes `value` little-endian, zero-padded to `size` bytes.
///
/// # Errors
///
/// Returns an error if the value does not fit into `size` bytes, or on I/O failure.
fn write_uint<O: Write>(output: &mut O, value: &BoxedUint, size: usize) -> Result<(), Error> {
    // Both buffers can hold secret key bytes: they are wiped on drop, and the output buffer is allocated at its
    // final size so that no reallocation leaves a copy behind.
    let trimmed = Zeroizing::new(value.to_be_bytes_trimmed_vartime().into_vec());
    if trimmed.len() > size {
        return Err(error!("Key component does not fit into {size} bytes."));
    }
    let mut vec = Zeroizing::new(vec![0u8; size]);
    for (dst, src) in vec.iter_mut().zip(trimmed.iter().rev()) {
        *dst = *src;
    }

    output.write_all(&vec)
}

/// Reads a key component of `size` little-endian bytes.
fn read_uint<I: Read>(input: &mut I, size: usize) -> Result<BoxedUint, Error> {
    // The buffer can hold a secret key component: wiped on drop, also on the error paths.
    let mut buffer = Zeroizing::new(vec![0; size]);
    input.read_exact(&mut buffer)?;
    uint_from_le(&buffer)
}

/// Converts little-endian bytes into an integer wide enough for them.
fn uint_from_le(bytes: &[u8]) -> Result<BoxedUint, Error> {
    let bits = u32::try_from(bytes.len())
        .ok()
        .and_then(|len| len.checked_mul(8))
        .ok_or_else(|| error!("Key component is too large."))?;
    BoxedUint::from_le_slice(bytes, bits).map_err(|_| error!("Invalid key data."))
}

/// Whether two integers have the same value, whatever their storage widths.
///
/// Variable time: used only to check a key file against itself, where the file's owner knows every value.
fn same_value(a: &BoxedUint, b: &BoxedUint) -> bool {
    let a = Zeroizing::new(a.to_be_bytes_trimmed_vartime().into_vec());
    let b = Zeroizing::new(b.to_be_bytes_trimmed_vartime().into_vec());
    *a == *b
}

/// Whether `value` is zero or one: no key component can be.
fn is_trivial(value: &BoxedUint) -> bool {
    value.bit_width_vartime() <= 1
}

/// Maps an `rsa` error onto a message that carries no key material.
///
/// `rsa` errors name the kind of defect only; they never contain a value.
#[expect(
    clippy::needless_pass_by_value,
    reason = "used as a map_err closure; the error is formatted, not stored"
)]
fn key_err(err: rsa::Error) -> Error {
    error!("{err}")
}

/// A PBO entry's lowercased raw name bytes paired with its contents.
type NameFilePair<'a> = (Vec<u8>, &'a [u8]);

/// Smallest key length accepted, in bits.
const MIN_KEY_BITS: u32 = 288;
/// Smallest key length that `sign` and `generate` accept, in bits: the minimum of the Windows `CryptoAPI` RSA
/// signature key (BI's tools and the game cannot use smaller ones). PKCS#1 v1.5 padding of a `SHA-1` hash needs
/// 368 bits at least. Smaller keys can still be read, and signatures made with them verified.
const MIN_SIGN_BITS: u32 = 384;
/// Largest key length accepted, in bits: the largest RSA key the Windows `CryptoAPI` (which BI's key format comes
/// from) handles. Bigger keys would only make hostile files expensive to read.
const MAX_KEY_BITS: u32 = 16384;

/// bType, bVersion and reserved of a private key blob (`PRIVATEKEYBLOB`, version 2), as a little-endian word.
const PRIVATE_BLOB: u32 = 0x0207;
/// The same for a public key blob (`PUBLICKEYBLOB`).
const PUBLIC_BLOB: u32 = 0x0206;
/// `aiKeyAlg` of every key: `CALG_RSA_SIGN`.
const KEY_ALG: u32 = 0x2400;
/// Magic of a private key blob.
const PRIVATE_MAGIC: [u8; 4] = *b"RSA2";
/// Magic of a public key blob.
const PUBLIC_MAGIC: [u8; 4] = *b"RSA1";

/// Reads and checks the 12 bytes of a `CryptoAPI` key blob header that follow the blob length: type and
/// version, key algorithm and magic.
///
/// # Errors
///
/// Returns an error on I/O failure or if the header is not the one of a `kind` key. `file` names the kind of file
/// ("private key", "public key", "signature") in the message.
fn check_blob_header<I: Read>(
    input: &mut I,
    blob: u32,
    magic: [u8; 4],
    file: &str,
    kind: &str,
) -> Result<(), Error> {
    let found_blob = input.read_u32::<LittleEndian>()?;
    let found_alg = input.read_u32::<LittleEndian>()?;
    let mut found_magic = [0; 4];
    input.read_exact(&mut found_magic)?;
    if found_blob != blob || found_alg != KEY_ALG || found_magic != magic {
        return Err(error!(
            "Invalid {file} file (bad header: not a {kind} key blob)."
        ));
    }
    Ok(())
}

/// Validates a key length read from a key or signature file.
///
/// # Errors
///
/// Returns an error if the length is not a sane RSA key length.
fn check_key_length(length: u32) -> Result<(), Error> {
    if !(MIN_KEY_BITS..=MAX_KEY_BITS).contains(&length) {
        return Err(error!(
            "Invalid key length: {length} (supported: {MIN_KEY_BITS} to {MAX_KEY_BITS} bits)."
        ));
    }
    Ok(())
}

/// Refuses key lengths that cannot sign.
///
/// # Errors
///
/// Returns an error if `length` is below the 384-bit `CryptoAPI` minimum.
fn check_sign_length(length: u32) -> Result<(), Error> {
    if length < MIN_SIGN_BITS {
        return Err(error!(
            "A {length}-bit key is smaller than the {MIN_SIGN_BITS}-bit CryptoAPI minimum and cannot sign."
        ));
    }
    Ok(())
}

/// The default signature file of `pbo_path`: `<pbo>.<key name>.bisign`.
///
/// The key name is read from the (untrusted) key file, so it must be a plain file name part:
/// `Path::set_extension` panics on a path separator, and a name must not steer the file elsewhere.
///
/// # Errors
///
/// Returns an error if the key name is empty or contains a path separator, `:` or a control
/// character.
pub fn signature_path(pbo_path: &Path, key_name: &str) -> Result<PathBuf, Error> {
    if key_name.is_empty()
        || key_name
            .chars()
            .any(|c| matches!(c, '/' | '\\' | ':') || c.is_control())
    {
        return Err(error!(
            "The key name {key_name:?} cannot be used in a file name; pass the signature path explicitly."
        ));
    }
    let mut path = pbo_path.to_path_buf();
    path.set_extension(format!("pbo.{key_name}.bisign"));
    Ok(path)
}

/// SHA-1 of the lowercased names of the non-empty entries, in byte order.
fn namehash(pbo: &PBO) -> [u8; 20] {
    let mut files_sorted: Vec<NameFilePair<'_>> = pbo
        .entries()
        .map(|(a, b)| (pbo.name_bytes(a).to_ascii_lowercase(), b))
        .collect();
    files_sorted.sort_by(|a, b| a.0.cmp(&b.0));

    let mut h = Sha1::new();

    for (name, data) in &files_sorted {
        if data.is_empty() {
            continue;
        }

        h.update(name);
    }

    h.finalize().into()
}

/// SHA-1 of the entries the signature `version` covers.
fn filehash(pbo: &PBO, version: BISignVersion) -> [u8; 20] {
    let mut h = Sha1::new();
    let mut nothing = true;

    for (name, data) in pbo.entries() {
        // file names are never empty, so there is always at least one (possibly empty) part
        let ext = name.split('.').next_back().unwrap_or("");

        match version {
            BISignVersion::V2 => {
                if ext == "paa"
                    || ext == "jpg"
                    || ext == "p3d"
                    || ext == "tga"
                    || ext == "rvmat"
                    || ext == "lip"
                    || ext == "ogg"
                    || ext == "wss"
                    || ext == "png"
                    || ext == "rtm"
                    || ext == "pac"
                    || ext == "fxy"
                    || ext == "wrp"
                {
                    continue;
                }
            }
            BISignVersion::V3 => {
                // "c": DayZ's DSSignFile also hashes Enforce Script files (verified against DSSignFile.exe
                // from DayZ Tools); without it a DayZ server rejects the signature of a script mod
                if ext != "sqf"
                    && ext != "c"
                    && ext != "inc"
                    && ext != "bikb"
                    && ext != "ext"
                    && ext != "fsm"
                    && ext != "sqm"
                    && ext != "hpp"
                    && ext != "cfg"
                    && ext != "sqs"
                    && ext != "h"
                {
                    continue;
                }
            }
        }

        h.update(data);
        nothing = false;
    }

    match version {
        BISignVersion::V2 => {
            if nothing {
                h.update(b"nothing");
            }
        }
        BISignVersion::V3 => {
            if nothing {
                h.update(b"gnihton");
            }
        }
    }

    h.finalize().into()
}

/// The three padded hashes that BI signs, big-endian, `length / 8` bytes each.
fn generate_hashes(
    pbo: &PBO,
    version: BISignVersion,
    length: u32,
    signing: bool,
) -> Result<[Vec<u8>; 3], Error> {
    // the SHA-1 of the PBO's contents: computed while reading for a PBO that was read (a stored trailer that
    // differs is an error), the one `PBO::write` would produce for one that was not read
    let checksum = pbo.trailer_checksum(signing)?;
    let hash1 = &checksum[..];

    let namehash = namehash(pbo);
    // the prefix part both of the following hashes end with
    let mut suffix = Vec::new();
    if let Some(prefix) = pbo.prefix() {
        suffix.extend(pbo.extension_bytes(prefix));
        if !prefix.ends_with('\\') {
            suffix.push(b'\\');
        }
    }

    let mut h = Sha1::new();
    h.update(hash1);
    h.update(namehash);
    h.update(&suffix);
    let hash2 = h.finalize();

    let mut h = Sha1::new();
    h.update(filehash(pbo, version));
    h.update(namehash);
    h.update(&suffix);
    let hash3 = h.finalize();

    let size = usize::try_from(length / 8).map_err(|_| error!("Invalid key length: {length}."))?;
    Ok([
        pad_hash(hash1, size)?,
        pad_hash(&hash2, size)?,
        pad_hash(&hash3, size)?,
    ])
}

/// The PKCS#1 v1.5 (`SHA-1`) padded block of `hash`, `size` bytes big-endian.
fn pad_hash(hash: &[u8], size: usize) -> Result<Vec<u8>, Error> {
    if size < 36 {
        return Err(error!("Key length too small: {size} bytes."));
    }
    let mut vec: Vec<u8> = Vec::new();

    vec.push(0);
    vec.push(1);
    vec.resize(size - 36, 255);
    vec.extend(b"\x00\x30\x21\x30\x09\x06\x05\x2b");
    vec.extend(b"\x0e\x03\x02\x1a\x05\x00\x04\x14");
    vec.extend(hash);

    Ok(vec)
}

/// `bytes` without its leading zero bytes.
fn trim_zeros(bytes: &[u8]) -> &[u8] {
    let start = bytes.iter().position(|&b| b != 0).unwrap_or(bytes.len());
    bytes.get(start..).unwrap_or_default()
}

/// Lowercase hex of a number (`0` for zero).
fn hex(bytes: &[u8]) -> String {
    if bytes.is_empty() {
        return "0".to_string();
    }
    let mut out = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        // writing into a String cannot fail
        let _ = write!(out, "{b:02x}");
    }
    out
}

/// The two numbers as hex, reduced to the hashes if their padding is the same.
fn display_hashes(signed: &[u8], real: &[u8]) -> (String, String) {
    let hex_signed = hex(signed);
    let hex_real = hex(real);

    if hex_signed.len() != hex_real.len() || hex_signed.len() <= 40 {
        return (hex_signed, hex_real);
    }

    let (signed_padding, signed_hash) = hex_signed.split_at(hex_signed.len() - 40);
    let (real_padding, real_hash) = hex_real.split_at(hex_real.len() - 40);

    if signed_padding == real_padding {
        (signed_hash.to_string(), real_hash.to_string())
    } else {
        (hex_signed, hex_real)
    }
}

impl BIPrivateKey {
    /// The key name, as stored in the key file.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Reads a private key from the given input.
    ///
    /// # Errors
    ///
    /// Returns an error if the input is not a valid private key.
    pub fn read<I: Read>(input: &mut I) -> Result<BIPrivateKey, Error> {
        let name = input.read_cstring()?;
        let temp = input.read_u32::<LittleEndian>()?;
        check_blob_header(input, PRIVATE_BLOB, PRIVATE_MAGIC, "private key", "private")?;
        let length = input.read_u32::<LittleEndian>()?;
        let exponent = input.read_u32::<LittleEndian>()?;

        check_key_length(length)?;
        if temp != length / 16 * 9 + 20 {
            return Err(error!("Invalid private key file (bad length field)."));
        }
        if length % 16 != 0 {
            return Err(error!(
                "Invalid private key file (the length {length} is not a multiple of 16)."
            ));
        }

        let full = (length / 8) as usize;
        let half = (length / 16) as usize;
        // Everything but `n` is secret: wiped on drop, also on the error returns below.
        let n = read_uint(input, full)?;
        let p = Zeroizing::new(read_uint(input, half)?);
        let q = Zeroizing::new(read_uint(input, half)?);
        let exp_p = Zeroizing::new(read_uint(input, half)?);
        let exp_q = Zeroizing::new(read_uint(input, half)?);
        let iqmp = Zeroizing::new(read_uint(input, half)?);
        let d = Zeroizing::new(read_uint(input, full)?);

        // `rsa` would reject most of these, but some values would reach its arithmetic first (a modulus of
        // one, a prime of zero), so every component is checked here.
        for value in [&n, &*p, &*q, &*exp_p, &*exp_q, &*iqmp, &*d] {
            if is_trivial(value) {
                return Err(error!("Invalid private key (a component is zero or one)."));
            }
        }
        if n.bit_width_vartime() != length {
            return Err(error!(
                "Invalid private key file (the modulus is not {length} bits wide)."
            ));
        }
        // `from_components` takes its numbers by value: the key owns (and wipes) copies, ours are wiped here.
        let key = PrivateKey::from_components(
            n,
            BoxedUint::from(u64::from(exponent)),
            (*d).clone(),
            vec![(*p).clone(), (*q).clone()],
        )
        .map_err(key_err)
        .prepend_error("Invalid private key:")?;

        // `rsa` recomputes the CRT values from `d`, `p` and `q`; the file's copies must agree.
        let consistent = match (
            key.dp(),
            key.dq(),
            key.crt_coefficient().map(Zeroizing::new),
        ) {
            (Some(dp), Some(dq), Some(qinv)) => {
                same_value(dp, &exp_p) && same_value(dq, &exp_q) && same_value(&qinv, &iqmp)
            }
            _ => false,
        };
        if !consistent {
            return Err(error!(
                "Invalid private key (CRT values do not match the primes)."
            ));
        }

        Ok(BIPrivateKey {
            name,
            length,
            exponent,
            key,
        })
    }

    /// Generate a new private key with the given name and bitlength, with the exponent 65537.
    ///
    /// Arma 3 uses 1024 bit keys. The length must be a multiple of 16 (the key file layout) between 384 bits (the
    /// `CryptoAPI` minimum, see [`BIPrivateKey::sign`]) and 16384 bits. Primes come from the operating system's
    /// random number generator.
    ///
    /// # Errors
    ///
    /// Returns an error if `length` is not usable or the keypair cannot be generated.
    pub fn generate(length: u32, name: String) -> Result<BIPrivateKey, Error> {
        Self::generate_with_rng(length, name, &mut SysRng)
    }

    /// [`generate`](Self::generate) with a caller-supplied random number generator (seeded ones in tests).
    pub(crate) fn generate_with_rng<R: TryCryptoRng + ?Sized>(
        length: u32,
        name: String,
        rng: &mut R,
    ) -> Result<BIPrivateKey, Error> {
        check_sign_length(length)?;
        check_key_length(length)?;
        if !length.is_multiple_of(16) {
            return Err(error!(
                "Invalid key length: {length} (it must be a multiple of 16)."
            ));
        }
        let exponent = 65537;
        // `rsa` refuses anything below 1024 bits by default; BI keys may be smaller (down to 384 bits for
        // signing), so the unchecked variant is used and the size limits are ours.
        let bits = usize::try_from(length).map_err(|_| error!("Invalid key length: {length}."))?;
        let key =
            PrivateKey::new_with_exp_unchecked(rng, bits, BoxedUint::from(u64::from(exponent)))
                .map_err(key_err)
                .prepend_error("Failed to generate keypair:")?;
        if key.n().as_ref().bit_width_vartime() != length {
            return Err(error!(
                "Failed to generate keypair: the modulus is not {length} bits wide."
            ));
        }

        Ok(BIPrivateKey {
            name,
            length,
            exponent,
            key,
        })
    }

    /// Returns the public key for this private key.
    ///
    /// # Errors
    ///
    /// Returns an error if the key material is invalid.
    pub fn to_public_key(&self) -> Result<BIPublicKey, Error> {
        Ok(BIPublicKey {
            name: self.name.clone(),
            length: self.length,
            exponent: self.exponent,
            key: self.key.to_public_key(),
        })
    }

    /// Signs the given PBO with this private key.
    ///
    /// # Errors
    ///
    /// Returns an error if the key is below 384 bits (the `CryptoAPI` minimum), the PBO's stored SHA-1 trailer does
    /// not match its contents (a checksum mismatch: repack the PBO first), hashing fails or the RSA operation
    /// fails.
    pub fn sign(&self, pbo: &PBO, version: BISignVersion) -> Result<BISign, Error> {
        check_sign_length(self.length)?;
        let hashes = generate_hashes(pbo, version, self.length, true)?;
        let n = self.key.n().as_ref();
        let precision = n.bits_precision();

        // Blinding (base, exponent and CRT modulus) uses the OS RNG; it changes the computation, never the
        // result, so signatures stay deterministic. The result is checked against the public key, which
        // catches a faulty CRT computation before a bad signature is written.
        let mut rng = SysRng;
        let mut sign_one = |padded: &[u8]| -> Result<BoxedUint, Error> {
            let m = BoxedUint::from_be_slice(padded, precision)
                .map_err(|_| error!("The hash does not fit the key."))?;
            rsa_decrypt_and_check(&self.key, Some(&mut rng), &m).map_err(key_err)
        };
        let [h1, h2, h3] = &hashes;
        let (sig1, sig2, sig3) = (sign_one(h1)?, sign_one(h2)?, sign_one(h3)?);

        Ok(BISign {
            version,
            name: self.name.clone(),
            length: self.length,
            exponent: self.exponent,
            n: n.clone(),
            sig1,
            sig2,
            sig3,
        })
    }

    /// Write private key to output.
    ///
    /// # Errors
    ///
    /// Returns an error on I/O failure.
    pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
        output
            .write_cstring(&self.name)
            .prepend_error("Key name:")?;
        output.write_u32::<LittleEndian>(self.length / 16 * 9 + 20)?;
        output.write_all(b"\x07\x02\x00\x00\x00\x24\x00\x00")?;
        output.write_all(b"RSA2")?;
        output.write_u32::<LittleEndian>(self.length)?;
        output.write_u32::<LittleEndian>(self.exponent)?;
        let full = (self.length / 8) as usize;
        let half = (self.length / 16) as usize;
        let primes = self.key.primes();
        let (Some(p), Some(q)) = (primes.first(), primes.get(1)) else {
            return Err(error!("Invalid private key (missing primes)."));
        };
        // The CRT values are recomputed from `d`, `p` and `q`; `read` checks that the file holds the same.
        let (Some(exp_p), Some(exp_q), Some(iqmp)) = (
            self.key.dp(),
            self.key.dq(),
            self.key.crt_coefficient().map(Zeroizing::new),
        ) else {
            return Err(error!("Invalid private key (missing CRT values)."));
        };
        write_uint(output, self.key.n().as_ref(), full)?;
        write_uint(output, p.as_ref(), half)?;
        write_uint(output, q.as_ref(), half)?;
        write_uint(output, exp_p, half)?;
        write_uint(output, exp_q, half)?;
        write_uint(output, &iqmp, half)?;
        write_uint(output, self.key.d(), full)?;
        Ok(())
    }
}

impl BIPublicKey {
    /// The key name, as stored in the key file.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Reads a public key from the given input.
    ///
    /// # Errors
    ///
    /// Returns an error if the input is not a valid public key.
    pub fn read<I: Read>(input: &mut I) -> Result<BIPublicKey, Error> {
        let name = input.read_cstring()?;
        let temp = input.read_u32::<LittleEndian>()?;
        check_blob_header(input, PUBLIC_BLOB, PUBLIC_MAGIC, "public key", "public")?;
        let length = input.read_u32::<LittleEndian>()?;
        let exponent = input.read_u32::<LittleEndian>()?;

        check_key_length(length)?;
        if temp != length / 8 + 20 {
            return Err(error!("Invalid public key file (bad length field)."));
        }

        let n = read_uint(input, (length / 8) as usize)?;
        // The modulus must be exactly `length` bits wide (a key frame bigger than its number, or a length that is
        // no multiple of 8, is rejected). BI keys down to 288 bits are accepted, `rsa`'s default limits (1024 to
        // 8192 bits) are widened to exactly this size.
        let length_bits = length as usize;
        let key = PublicKey::new_with_size_limits(
            n,
            BoxedUint::from(u64::from(exponent)),
            length_bits..=length_bits,
        )
        .map_err(key_err)
        .prepend_error("Invalid public key:")?;

        Ok(BIPublicKey {
            name,
            length,
            exponent,
            key,
        })
    }

    /// Verifies a signature against this public key.
    ///
    /// # Errors
    ///
    /// Returns an error if the signature was made with a different key, a signature value is not smaller than the
    /// modulus, the PBO's stored SHA-1 trailer does not match its contents (a checksum mismatch), hashing fails or
    /// one of the signature hashes doesn't match.
    pub fn verify(&self, pbo: &PBO, signature: &BISign) -> Result<(), Error> {
        let n = self.key.n().as_ref();
        // a signature carries the public key it was made with: compare before anything else, so that a wrong key
        // is reported as such and not as a defect of the signature values
        if signature.length != self.length || !same_value(&signature.n, n) {
            return Err(error!(
                "The signature was made with a different key (signature: {}, {} bits; this key: {}, {} bits).",
                printable(&signature.name),
                signature.length,
                printable(&self.name),
                self.length
            ));
        }
        let hashes = generate_hashes(pbo, signature.version, self.length, false)?;
        let precision = n.bits_precision();

        let values = [&signature.sig1, &signature.sig2, &signature.sig3];
        let mut signed = Vec::with_capacity(values.len());
        for (i, value) in values.into_iter().enumerate() {
            let number = i + 1;
            // a signature value is below n; a bigger one (or one too wide for the key) is no signature
            let value = BoxedUint::from_be_slice(&value.to_be_bytes_trimmed_vartime(), precision)
                .ok()
                .filter(|value| value < n)
                .ok_or_else(|| error!("Signature {number} is not smaller than the modulus."))?;
            signed.push(rsa_encrypt(&self.key, &value).map_err(key_err)?);
        }

        // Plain `==` on the trimmed bytes: both sides are public (the recovered block and the hashes of the
        // PBO), so no constant-time comparison is needed.
        for (i, (signed, real)) in signed.iter().zip(&hashes).enumerate() {
            let signed = signed.to_be_bytes_trimmed_vartime();
            let real = trim_zeros(real);
            if *signed != *real {
                let (s, r) = display_hashes(&signed, real);
                return Err(error!(
                    "Hash {} doesn't match\nSigned hash: {}\nReal hash:   {}",
                    i + 1,
                    s,
                    r
                ));
            }
        }

        Ok(())
    }

    /// Write public key to output.
    ///
    /// # Errors
    ///
    /// Returns an error on I/O failure.
    pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
        output
            .write_cstring(&self.name)
            .prepend_error("Key name:")?;
        output.write_u32::<LittleEndian>(self.length / 8 + 20)?;
        output.write_all(b"\x06\x02\x00\x00\x00\x24\x00\x00")?;
        output.write_all(b"RSA1")?;
        output.write_u32::<LittleEndian>(self.length)?;
        output.write_u32::<LittleEndian>(self.exponent)?;
        write_uint(output, self.key.n().as_ref(), (self.length / 8) as usize)?;
        Ok(())
    }
}

impl From<BISignVersion> for u32 {
    fn from(val: BISignVersion) -> Self {
        match val {
            BISignVersion::V2 => 2,
            BISignVersion::V3 => 3,
        }
    }
}

/// BI signature (.bisign)
impl BISign {
    /// Reads a signature from the given input.
    ///
    /// # Errors
    ///
    /// Returns an error if the input is not a valid signature.
    pub fn read<I: Read>(input: &mut I) -> Result<BISign, Error> {
        let name = input.read_cstring()?;
        let temp = input.read_u32::<LittleEndian>()?;
        check_blob_header(input, PUBLIC_BLOB, PUBLIC_MAGIC, "signature", "public")?;
        let length = input.read_u32::<LittleEndian>()?;
        let exponent = input.read_u32::<LittleEndian>()?;

        check_key_length(length)?;
        if temp != length / 8 + 20 {
            return Err(error!("Invalid signature file (bad length field)."));
        }

        let size = (length / 8) as usize;
        let n = read_uint(input, size)?;
        if n.bit_width_vartime() != length {
            return Err(error!(
                "Invalid signature file (the modulus is not {length} bits wide)."
            ));
        }

        input.read_u32::<LittleEndian>()?;
        let sig1 = read_uint(input, size)?;

        let version = match input.read_u32::<LittleEndian>()? {
            2 => BISignVersion::V2,
            3 => BISignVersion::V3,
            _ => {
                return Err(error!("Unknown BISign version."));
            }
        };

        input.read_u32::<LittleEndian>()?;
        let sig2 = read_uint(input, size)?;

        input.read_u32::<LittleEndian>()?;
        let sig3 = read_uint(input, size)?;

        Ok(BISign {
            version,
            name,
            length,
            exponent,
            n,
            sig1,
            sig2,
            sig3,
        })
    }

    /// Writes the signature to the given output.
    ///
    /// # Errors
    ///
    /// Returns an error on I/O failure.
    pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
        output
            .write_cstring(&self.name)
            .prepend_error("Key name:")?;
        output.write_u32::<LittleEndian>(self.length / 8 + 20)?;
        output.write_all(b"\x06\x02\x00\x00\x00\x24\x00\x00")?;
        output.write_all(b"RSA1")?;
        output.write_u32::<LittleEndian>(self.length)?;
        output.write_u32::<LittleEndian>(self.exponent)?;
        write_uint(output, &self.n, (self.length / 8) as usize)?;
        output.write_u32::<LittleEndian>(self.length / 8)?;
        write_uint(output, &self.sig1, (self.length / 8) as usize)?;
        output.write_u32::<LittleEndian>(self.version.into())?;
        output.write_u32::<LittleEndian>(self.length / 8)?;
        write_uint(output, &self.sig2, (self.length / 8) as usize)?;
        output.write_u32::<LittleEndian>(self.length / 8)?;
        write_uint(output, &self.sig3, (self.length / 8) as usize)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    //! Key generation is tested here because the seeded entry point `generate_with_rng` is private to the crate.
    #![expect(
        clippy::many_single_char_names,
        reason = "the names of the RSA numbers: n, e, d, p, q"
    )]

    use std::fs;
    use std::io::Cursor;

    use num_bigint::BigUint;
    use rand_chacha::ChaCha20Rng;
    use rand_core::SeedableRng;

    use super::*;

    fn seeded(seed: u64, bits: u32) -> BIPrivateKey {
        let mut rng = ChaCha20Rng::seed_from_u64(seed);
        BIPrivateKey::generate_with_rng(bits, "gen".to_string(), &mut rng).unwrap()
    }

    fn bn(value: &BoxedUint) -> BigUint {
        BigUint::from_bytes_be(&value.to_be_bytes_trimmed_vartime())
    }

    fn file(key: &BIPrivateKey) -> Vec<u8> {
        let mut out = Vec::new();
        key.write(&mut out).unwrap();
        out
    }

    #[test]
    fn generated_key_is_valid() {
        for (seed, bits) in [(1u64, 384u32), (2, 1024)] {
            let key = seeded(seed, bits);
            assert_eq!((key.length, key.exponent), (bits, 65537));
            let n = bn(key.key.n().as_ref());
            assert_eq!(n.bits(), u64::from(bits));
            let primes = key.key.primes();
            let (p, q) = (bn(&primes[0]), bn(&primes[1]));
            let (d, e) = (bn(key.key.d()), BigUint::from(65537u32));
            let one = BigUint::from(1u32);

            // p * q = n
            assert_eq!(&p * &q, n);

            // e * d = 1 mod phi(n); `rsa` computes d from phi (not from lambda)
            let (p1, q1) = (&p - &one, &q - &one);
            let phi = &p1 * &q1;
            assert_eq!((&e * &d) % &phi, one, "e * d mod phi(n)");

            // CRT values
            assert_eq!(&d % &p1, bn(key.key.dp().unwrap()));
            assert_eq!(&d % &q1, bn(key.key.dq().unwrap()));
            let qinv = key.key.crt_coefficient().unwrap();
            assert_eq!((bn(&qinv) * &q) % &p, one, "qinv * q mod p");

            // the key file round-trips byte for byte
            let bytes = file(&key);
            let again = BIPrivateKey::read(&mut Cursor::new(&bytes)).unwrap();
            assert_eq!(file(&again), bytes);
            assert_eq!(again.name(), "gen");
        }
    }

    #[test]
    fn generated_key_signs_and_verifies() {
        let pbo_bytes = fs::read(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/bi/sign/testsig.pbo"
        ))
        .unwrap();
        let pbo = PBO::read(&mut Cursor::new(pbo_bytes)).unwrap();
        let key = seeded(3, 1024);
        let public = key.to_public_key().unwrap();
        for version in [BISignVersion::V2, BISignVersion::V3] {
            let signature = key.sign(&pbo, version).unwrap();
            public.verify(&pbo, &signature).unwrap();

            // the independent side: num-bigint's modular exponentiation recovers the padded hashes
            let hashes = generate_hashes(&pbo, version, 1024, false).unwrap();
            let n = bn(key.key.n().as_ref());
            let e = BigUint::from(65537u32);
            for (sig, hash) in [&signature.sig1, &signature.sig2, &signature.sig3]
                .into_iter()
                .zip(&hashes)
            {
                let back = bn(sig).modpow(&e, &n);
                assert_eq!(back.to_bytes_be(), trim_zeros(hash));
            }
        }
    }

    #[test]
    fn seeded_generation_is_deterministic() {
        assert_eq!(file(&seeded(4, 512)), file(&seeded(4, 512)));
        assert_ne!(file(&seeded(4, 512)), file(&seeded(5, 512)));
    }

    #[test]
    fn generation_with_the_os_rng_is_not_deterministic() {
        let a = BIPrivateKey::generate(384, "a".to_string()).unwrap();
        let b = BIPrivateKey::generate(384, "a".to_string()).unwrap();
        assert_ne!(file(&a), file(&b));
    }

    #[test]
    fn unusable_lengths_are_refused() {
        for bits in [0, 288, 368, 383, 392, 400 + 8, MAX_KEY_BITS + 16] {
            assert!(
                BIPrivateKey::generate(bits, "x".to_string()).is_err(),
                "{bits}"
            );
        }
    }
}