1use std::fmt::Write as _;
4use std::io::{Error, Read, Write};
5use std::path::{Path, PathBuf};
6
7use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
8use getrandom::SysRng;
9use rsa::hazmat::{rsa_decrypt_and_check, rsa_encrypt};
10use rsa::rand_core::TryCryptoRng;
11use rsa::traits::{PrivateKeyParts, PublicKeyParts};
12use rsa::{BoxedUint, PrivateKey, PublicKey};
13use sha1::{Digest, Sha1};
14use zeroize::Zeroizing;
15
16use crate::error::{ErrorExt, printable};
17use crate::io::{ReadExt, WriteExt};
18use crate::pbo::PBO;
19
20pub struct BIPrivateKey {
22 name: String,
23 length: u32,
24 exponent: u32,
25 key: PrivateKey,
27}
28
29#[derive(Debug)]
31pub struct BIPublicKey {
32 name: String,
33 length: u32,
34 exponent: u32,
35 key: PublicKey,
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum BISignVersion {
42 V2,
44 V3,
46}
47
48#[derive(Debug)]
50pub struct BISign {
51 version: BISignVersion,
52 name: String,
53 length: u32,
54 exponent: u32,
55 n: BoxedUint,
56 sig1: BoxedUint,
57 sig2: BoxedUint,
58 sig3: BoxedUint,
59}
60
61impl std::fmt::Debug for BIPrivateKey {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 f.debug_struct("BIPrivateKey")
65 .field("name", &self.name)
66 .field("length", &self.length)
67 .finish_non_exhaustive()
68 }
69}
70
71fn write_uint<O: Write>(output: &mut O, value: &BoxedUint, size: usize) -> Result<(), Error> {
77 let trimmed = Zeroizing::new(value.to_be_bytes_trimmed_vartime().into_vec());
80 if trimmed.len() > size {
81 return Err(error!("Key component does not fit into {size} bytes."));
82 }
83 let mut vec = Zeroizing::new(vec![0u8; size]);
84 for (dst, src) in vec.iter_mut().zip(trimmed.iter().rev()) {
85 *dst = *src;
86 }
87
88 output.write_all(&vec)
89}
90
91fn read_uint<I: Read>(input: &mut I, size: usize) -> Result<BoxedUint, Error> {
93 let mut buffer = Zeroizing::new(vec![0; size]);
95 input.read_exact(&mut buffer)?;
96 uint_from_le(&buffer)
97}
98
99fn uint_from_le(bytes: &[u8]) -> Result<BoxedUint, Error> {
101 let bits = u32::try_from(bytes.len())
102 .ok()
103 .and_then(|len| len.checked_mul(8))
104 .ok_or_else(|| error!("Key component is too large."))?;
105 BoxedUint::from_le_slice(bytes, bits).map_err(|_| error!("Invalid key data."))
106}
107
108fn same_value(a: &BoxedUint, b: &BoxedUint) -> bool {
112 let a = Zeroizing::new(a.to_be_bytes_trimmed_vartime().into_vec());
113 let b = Zeroizing::new(b.to_be_bytes_trimmed_vartime().into_vec());
114 *a == *b
115}
116
117fn is_trivial(value: &BoxedUint) -> bool {
119 value.bit_width_vartime() <= 1
120}
121
122#[expect(
126 clippy::needless_pass_by_value,
127 reason = "used as a map_err closure; the error is formatted, not stored"
128)]
129fn key_err(err: rsa::Error) -> Error {
130 error!("{err}")
131}
132
133type NameFilePair<'a> = (Vec<u8>, &'a [u8]);
135
136const MIN_KEY_BITS: u32 = 288;
138const MIN_SIGN_BITS: u32 = 384;
142const MAX_KEY_BITS: u32 = 16384;
145
146const PRIVATE_BLOB: u32 = 0x0207;
148const PUBLIC_BLOB: u32 = 0x0206;
150const KEY_ALG: u32 = 0x2400;
152const PRIVATE_MAGIC: [u8; 4] = *b"RSA2";
154const PUBLIC_MAGIC: [u8; 4] = *b"RSA1";
156
157fn check_blob_header<I: Read>(
165 input: &mut I,
166 blob: u32,
167 magic: [u8; 4],
168 file: &str,
169 kind: &str,
170) -> Result<(), Error> {
171 let found_blob = input.read_u32::<LittleEndian>()?;
172 let found_alg = input.read_u32::<LittleEndian>()?;
173 let mut found_magic = [0; 4];
174 input.read_exact(&mut found_magic)?;
175 if found_blob != blob || found_alg != KEY_ALG || found_magic != magic {
176 return Err(error!(
177 "Invalid {file} file (bad header: not a {kind} key blob)."
178 ));
179 }
180 Ok(())
181}
182
183fn check_key_length(length: u32) -> Result<(), Error> {
189 if !(MIN_KEY_BITS..=MAX_KEY_BITS).contains(&length) {
190 return Err(error!(
191 "Invalid key length: {length} (supported: {MIN_KEY_BITS} to {MAX_KEY_BITS} bits)."
192 ));
193 }
194 Ok(())
195}
196
197fn check_sign_length(length: u32) -> Result<(), Error> {
203 if length < MIN_SIGN_BITS {
204 return Err(error!(
205 "A {length}-bit key is smaller than the {MIN_SIGN_BITS}-bit CryptoAPI minimum and cannot sign."
206 ));
207 }
208 Ok(())
209}
210
211pub fn signature_path(pbo_path: &Path, key_name: &str) -> Result<PathBuf, Error> {
221 if key_name.is_empty()
222 || key_name
223 .chars()
224 .any(|c| matches!(c, '/' | '\\' | ':') || c.is_control())
225 {
226 return Err(error!(
227 "The key name {key_name:?} cannot be used in a file name; pass the signature path explicitly."
228 ));
229 }
230 let mut path = pbo_path.to_path_buf();
231 path.set_extension(format!("pbo.{key_name}.bisign"));
232 Ok(path)
233}
234
235fn namehash(pbo: &PBO) -> [u8; 20] {
237 let mut files_sorted: Vec<NameFilePair<'_>> = pbo
238 .entries()
239 .map(|(a, b)| (pbo.name_bytes(a).to_ascii_lowercase(), b))
240 .collect();
241 files_sorted.sort_by(|a, b| a.0.cmp(&b.0));
242
243 let mut h = Sha1::new();
244
245 for (name, data) in &files_sorted {
246 if data.is_empty() {
247 continue;
248 }
249
250 h.update(name);
251 }
252
253 h.finalize().into()
254}
255
256fn filehash(pbo: &PBO, version: BISignVersion) -> [u8; 20] {
258 let mut h = Sha1::new();
259 let mut nothing = true;
260
261 for (name, data) in pbo.entries() {
262 let ext = name.split('.').next_back().unwrap_or("");
264
265 match version {
266 BISignVersion::V2 => {
267 if ext == "paa"
268 || ext == "jpg"
269 || ext == "p3d"
270 || ext == "tga"
271 || ext == "rvmat"
272 || ext == "lip"
273 || ext == "ogg"
274 || ext == "wss"
275 || ext == "png"
276 || ext == "rtm"
277 || ext == "pac"
278 || ext == "fxy"
279 || ext == "wrp"
280 {
281 continue;
282 }
283 }
284 BISignVersion::V3 => {
285 if ext != "sqf"
288 && ext != "c"
289 && ext != "inc"
290 && ext != "bikb"
291 && ext != "ext"
292 && ext != "fsm"
293 && ext != "sqm"
294 && ext != "hpp"
295 && ext != "cfg"
296 && ext != "sqs"
297 && ext != "h"
298 {
299 continue;
300 }
301 }
302 }
303
304 h.update(data);
305 nothing = false;
306 }
307
308 match version {
309 BISignVersion::V2 => {
310 if nothing {
311 h.update(b"nothing");
312 }
313 }
314 BISignVersion::V3 => {
315 if nothing {
316 h.update(b"gnihton");
317 }
318 }
319 }
320
321 h.finalize().into()
322}
323
324fn generate_hashes(
326 pbo: &PBO,
327 version: BISignVersion,
328 length: u32,
329 signing: bool,
330) -> Result<[Vec<u8>; 3], Error> {
331 let checksum = pbo.trailer_checksum(signing)?;
334 let hash1 = &checksum[..];
335
336 let namehash = namehash(pbo);
337 let mut suffix = Vec::new();
339 if let (Some(prefix), Some(prefix_bytes)) = (pbo.prefix(), pbo.prefix_bytes()) {
340 suffix.extend(prefix_bytes);
341 if !prefix.ends_with('\\') {
342 suffix.push(b'\\');
343 }
344 }
345
346 let mut h = Sha1::new();
347 h.update(hash1);
348 h.update(namehash);
349 h.update(&suffix);
350 let hash2 = h.finalize();
351
352 let mut h = Sha1::new();
353 h.update(filehash(pbo, version));
354 h.update(namehash);
355 h.update(&suffix);
356 let hash3 = h.finalize();
357
358 let size = usize::try_from(length / 8).map_err(|_| error!("Invalid key length: {length}."))?;
359 Ok([
360 pad_hash(hash1, size)?,
361 pad_hash(&hash2, size)?,
362 pad_hash(&hash3, size)?,
363 ])
364}
365
366fn pad_hash(hash: &[u8], size: usize) -> Result<Vec<u8>, Error> {
368 if size < 36 {
369 return Err(error!("Key length too small: {size} bytes."));
370 }
371 let mut vec: Vec<u8> = Vec::new();
372
373 vec.push(0);
374 vec.push(1);
375 vec.resize(size - 36, 255);
376 vec.extend(b"\x00\x30\x21\x30\x09\x06\x05\x2b");
377 vec.extend(b"\x0e\x03\x02\x1a\x05\x00\x04\x14");
378 vec.extend(hash);
379
380 Ok(vec)
381}
382
383fn trim_zeros(bytes: &[u8]) -> &[u8] {
385 let start = bytes.iter().position(|&b| b != 0).unwrap_or(bytes.len());
386 bytes.get(start..).unwrap_or_default()
387}
388
389fn hex(bytes: &[u8]) -> String {
391 if bytes.is_empty() {
392 return "0".to_string();
393 }
394 let mut out = String::with_capacity(bytes.len() * 2);
395 for b in bytes {
396 let _ = write!(out, "{b:02x}");
398 }
399 out
400}
401
402fn display_hashes(signed: &[u8], real: &[u8]) -> (String, String) {
404 let hex_signed = hex(signed);
405 let hex_real = hex(real);
406
407 if hex_signed.len() != hex_real.len() || hex_signed.len() <= 40 {
408 return (hex_signed, hex_real);
409 }
410
411 let (signed_padding, signed_hash) = hex_signed.split_at(hex_signed.len() - 40);
412 let (real_padding, real_hash) = hex_real.split_at(hex_real.len() - 40);
413
414 if signed_padding == real_padding {
415 (signed_hash.to_string(), real_hash.to_string())
416 } else {
417 (hex_signed, hex_real)
418 }
419}
420
421impl BIPrivateKey {
422 #[must_use]
424 pub fn name(&self) -> &str {
425 &self.name
426 }
427
428 pub fn read<I: Read>(input: &mut I) -> Result<BIPrivateKey, Error> {
434 let name = input.read_cstring()?;
435 let temp = input.read_u32::<LittleEndian>()?;
436 check_blob_header(input, PRIVATE_BLOB, PRIVATE_MAGIC, "private key", "private")?;
437 let length = input.read_u32::<LittleEndian>()?;
438 let exponent = input.read_u32::<LittleEndian>()?;
439
440 check_key_length(length)?;
441 if temp != length / 16 * 9 + 20 {
442 return Err(error!("Invalid private key file (bad length field)."));
443 }
444 if length % 16 != 0 {
445 return Err(error!(
446 "Invalid private key file (the length {length} is not a multiple of 16)."
447 ));
448 }
449
450 let full = (length / 8) as usize;
451 let half = (length / 16) as usize;
452 let n = read_uint(input, full)?;
454 let p = Zeroizing::new(read_uint(input, half)?);
455 let q = Zeroizing::new(read_uint(input, half)?);
456 let exp_p = Zeroizing::new(read_uint(input, half)?);
457 let exp_q = Zeroizing::new(read_uint(input, half)?);
458 let iqmp = Zeroizing::new(read_uint(input, half)?);
459 let d = Zeroizing::new(read_uint(input, full)?);
460
461 for value in [&n, &*p, &*q, &*exp_p, &*exp_q, &*iqmp, &*d] {
464 if is_trivial(value) {
465 return Err(error!("Invalid private key (a component is zero or one)."));
466 }
467 }
468 if n.bit_width_vartime() != length {
469 return Err(error!(
470 "Invalid private key file (the modulus is not {length} bits wide)."
471 ));
472 }
473 let key = PrivateKey::from_components(
475 n,
476 BoxedUint::from(u64::from(exponent)),
477 (*d).clone(),
478 vec![(*p).clone(), (*q).clone()],
479 )
480 .map_err(key_err)
481 .prepend_error("Invalid private key:")?;
482
483 let consistent = match (
485 key.dp(),
486 key.dq(),
487 key.crt_coefficient().map(Zeroizing::new),
488 ) {
489 (Some(dp), Some(dq), Some(qinv)) => {
490 same_value(dp, &exp_p) && same_value(dq, &exp_q) && same_value(&qinv, &iqmp)
491 }
492 _ => false,
493 };
494 if !consistent {
495 return Err(error!(
496 "Invalid private key (CRT values do not match the primes)."
497 ));
498 }
499
500 Ok(BIPrivateKey {
501 name,
502 length,
503 exponent,
504 key,
505 })
506 }
507
508 pub fn generate(length: u32, name: String) -> Result<BIPrivateKey, Error> {
518 Self::generate_with_rng(length, name, &mut SysRng)
519 }
520
521 pub(crate) fn generate_with_rng<R: TryCryptoRng + ?Sized>(
523 length: u32,
524 name: String,
525 rng: &mut R,
526 ) -> Result<BIPrivateKey, Error> {
527 check_sign_length(length)?;
528 check_key_length(length)?;
529 if !length.is_multiple_of(16) {
530 return Err(error!(
531 "Invalid key length: {length} (it must be a multiple of 16)."
532 ));
533 }
534 let exponent = 65537;
535 let bits = usize::try_from(length).map_err(|_| error!("Invalid key length: {length}."))?;
538 let key =
539 PrivateKey::new_with_exp_unchecked(rng, bits, BoxedUint::from(u64::from(exponent)))
540 .map_err(key_err)
541 .prepend_error("Failed to generate keypair:")?;
542 if key.n().as_ref().bit_width_vartime() != length {
543 return Err(error!(
544 "Failed to generate keypair: the modulus is not {length} bits wide."
545 ));
546 }
547
548 Ok(BIPrivateKey {
549 name,
550 length,
551 exponent,
552 key,
553 })
554 }
555
556 pub fn to_public_key(&self) -> Result<BIPublicKey, Error> {
562 Ok(BIPublicKey {
563 name: self.name.clone(),
564 length: self.length,
565 exponent: self.exponent,
566 key: self.key.to_public_key(),
567 })
568 }
569
570 pub fn sign(&self, pbo: &PBO, version: BISignVersion) -> Result<BISign, Error> {
578 check_sign_length(self.length)?;
579 let hashes = generate_hashes(pbo, version, self.length, true)?;
580 let n = self.key.n().as_ref();
581 let precision = n.bits_precision();
582
583 let mut rng = SysRng;
587 let mut sign_one = |padded: &[u8]| -> Result<BoxedUint, Error> {
588 let m = BoxedUint::from_be_slice(padded, precision)
589 .map_err(|_| error!("The hash does not fit the key."))?;
590 rsa_decrypt_and_check(&self.key, Some(&mut rng), &m).map_err(key_err)
591 };
592 let [h1, h2, h3] = &hashes;
593 let (sig1, sig2, sig3) = (sign_one(h1)?, sign_one(h2)?, sign_one(h3)?);
594
595 Ok(BISign {
596 version,
597 name: self.name.clone(),
598 length: self.length,
599 exponent: self.exponent,
600 n: n.clone(),
601 sig1,
602 sig2,
603 sig3,
604 })
605 }
606
607 pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
613 output
614 .write_cstring(&self.name)
615 .prepend_error("Key name:")?;
616 output.write_u32::<LittleEndian>(self.length / 16 * 9 + 20)?;
617 output.write_all(b"\x07\x02\x00\x00\x00\x24\x00\x00")?;
618 output.write_all(b"RSA2")?;
619 output.write_u32::<LittleEndian>(self.length)?;
620 output.write_u32::<LittleEndian>(self.exponent)?;
621 let full = (self.length / 8) as usize;
622 let half = (self.length / 16) as usize;
623 let primes = self.key.primes();
624 let (Some(p), Some(q)) = (primes.first(), primes.get(1)) else {
625 return Err(error!("Invalid private key (missing primes)."));
626 };
627 let (Some(exp_p), Some(exp_q), Some(iqmp)) = (
629 self.key.dp(),
630 self.key.dq(),
631 self.key.crt_coefficient().map(Zeroizing::new),
632 ) else {
633 return Err(error!("Invalid private key (missing CRT values)."));
634 };
635 write_uint(output, self.key.n().as_ref(), full)?;
636 write_uint(output, p.as_ref(), half)?;
637 write_uint(output, q.as_ref(), half)?;
638 write_uint(output, exp_p, half)?;
639 write_uint(output, exp_q, half)?;
640 write_uint(output, &iqmp, half)?;
641 write_uint(output, self.key.d(), full)?;
642 Ok(())
643 }
644}
645
646impl BIPublicKey {
647 #[must_use]
649 pub fn name(&self) -> &str {
650 &self.name
651 }
652
653 pub fn read<I: Read>(input: &mut I) -> Result<BIPublicKey, Error> {
659 let name = input.read_cstring()?;
660 let temp = input.read_u32::<LittleEndian>()?;
661 check_blob_header(input, PUBLIC_BLOB, PUBLIC_MAGIC, "public key", "public")?;
662 let length = input.read_u32::<LittleEndian>()?;
663 let exponent = input.read_u32::<LittleEndian>()?;
664
665 check_key_length(length)?;
666 if temp != length / 8 + 20 {
667 return Err(error!("Invalid public key file (bad length field)."));
668 }
669
670 let n = read_uint(input, (length / 8) as usize)?;
671 let length_bits = length as usize;
675 let key = PublicKey::new_with_size_limits(
676 n,
677 BoxedUint::from(u64::from(exponent)),
678 length_bits..=length_bits,
679 )
680 .map_err(key_err)
681 .prepend_error("Invalid public key:")?;
682
683 Ok(BIPublicKey {
684 name,
685 length,
686 exponent,
687 key,
688 })
689 }
690
691 pub fn verify(&self, pbo: &PBO, signature: &BISign) -> Result<(), Error> {
699 let n = self.key.n().as_ref();
700 if signature.length != self.length || !same_value(&signature.n, n) {
703 return Err(error!(
704 "The signature was made with a different key (signature: {}, {} bits; this key: {}, {} bits).",
705 printable(&signature.name),
706 signature.length,
707 printable(&self.name),
708 self.length
709 ));
710 }
711 let hashes = generate_hashes(pbo, signature.version, self.length, false)?;
712 let precision = n.bits_precision();
713
714 let values = [&signature.sig1, &signature.sig2, &signature.sig3];
715 let mut signed = Vec::with_capacity(values.len());
716 for (i, value) in values.into_iter().enumerate() {
717 let number = i + 1;
718 let value = BoxedUint::from_be_slice(&value.to_be_bytes_trimmed_vartime(), precision)
720 .ok()
721 .filter(|value| value < n)
722 .ok_or_else(|| error!("Signature {number} is not smaller than the modulus."))?;
723 signed.push(rsa_encrypt(&self.key, &value).map_err(key_err)?);
724 }
725
726 for (i, (signed, real)) in signed.iter().zip(&hashes).enumerate() {
729 let signed = signed.to_be_bytes_trimmed_vartime();
730 let real = trim_zeros(real);
731 if *signed != *real {
732 let (s, r) = display_hashes(&signed, real);
733 return Err(error!(
734 "Hash {} doesn't match\nSigned hash: {}\nReal hash: {}",
735 i + 1,
736 s,
737 r
738 ));
739 }
740 }
741
742 Ok(())
743 }
744
745 pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
751 output
752 .write_cstring(&self.name)
753 .prepend_error("Key name:")?;
754 output.write_u32::<LittleEndian>(self.length / 8 + 20)?;
755 output.write_all(b"\x06\x02\x00\x00\x00\x24\x00\x00")?;
756 output.write_all(b"RSA1")?;
757 output.write_u32::<LittleEndian>(self.length)?;
758 output.write_u32::<LittleEndian>(self.exponent)?;
759 write_uint(output, self.key.n().as_ref(), (self.length / 8) as usize)?;
760 Ok(())
761 }
762}
763
764impl From<BISignVersion> for u32 {
765 fn from(val: BISignVersion) -> Self {
766 match val {
767 BISignVersion::V2 => 2,
768 BISignVersion::V3 => 3,
769 }
770 }
771}
772
773impl BISign {
775 pub fn read<I: Read>(input: &mut I) -> Result<BISign, Error> {
781 let name = input.read_cstring()?;
782 let temp = input.read_u32::<LittleEndian>()?;
783 check_blob_header(input, PUBLIC_BLOB, PUBLIC_MAGIC, "signature", "public")?;
784 let length = input.read_u32::<LittleEndian>()?;
785 let exponent = input.read_u32::<LittleEndian>()?;
786
787 check_key_length(length)?;
788 if temp != length / 8 + 20 {
789 return Err(error!("Invalid signature file (bad length field)."));
790 }
791
792 let size = (length / 8) as usize;
793 let n = read_uint(input, size)?;
794 if n.bit_width_vartime() != length {
795 return Err(error!(
796 "Invalid signature file (the modulus is not {length} bits wide)."
797 ));
798 }
799
800 input.read_u32::<LittleEndian>()?;
801 let sig1 = read_uint(input, size)?;
802
803 let version = match input.read_u32::<LittleEndian>()? {
804 2 => BISignVersion::V2,
805 3 => BISignVersion::V3,
806 _ => {
807 return Err(error!("Unknown BISign version."));
808 }
809 };
810
811 input.read_u32::<LittleEndian>()?;
812 let sig2 = read_uint(input, size)?;
813
814 input.read_u32::<LittleEndian>()?;
815 let sig3 = read_uint(input, size)?;
816
817 Ok(BISign {
818 version,
819 name,
820 length,
821 exponent,
822 n,
823 sig1,
824 sig2,
825 sig3,
826 })
827 }
828
829 pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
835 output
836 .write_cstring(&self.name)
837 .prepend_error("Key name:")?;
838 output.write_u32::<LittleEndian>(self.length / 8 + 20)?;
839 output.write_all(b"\x06\x02\x00\x00\x00\x24\x00\x00")?;
840 output.write_all(b"RSA1")?;
841 output.write_u32::<LittleEndian>(self.length)?;
842 output.write_u32::<LittleEndian>(self.exponent)?;
843 write_uint(output, &self.n, (self.length / 8) as usize)?;
844 output.write_u32::<LittleEndian>(self.length / 8)?;
845 write_uint(output, &self.sig1, (self.length / 8) as usize)?;
846 output.write_u32::<LittleEndian>(self.version.into())?;
847 output.write_u32::<LittleEndian>(self.length / 8)?;
848 write_uint(output, &self.sig2, (self.length / 8) as usize)?;
849 output.write_u32::<LittleEndian>(self.length / 8)?;
850 write_uint(output, &self.sig3, (self.length / 8) as usize)?;
851 Ok(())
852 }
853}
854
855#[cfg(test)]
856mod tests {
857 #![expect(
859 clippy::many_single_char_names,
860 reason = "the names of the RSA numbers: n, e, d, p, q"
861 )]
862
863 use std::fs;
864 use std::io::Cursor;
865
866 use num_bigint::BigUint;
867 use rand_chacha::ChaCha20Rng;
868 use rand_core::SeedableRng;
869
870 use super::*;
871
872 fn seeded(seed: u64, bits: u32) -> BIPrivateKey {
873 let mut rng = ChaCha20Rng::seed_from_u64(seed);
874 BIPrivateKey::generate_with_rng(bits, "gen".to_string(), &mut rng).unwrap()
875 }
876
877 fn bn(value: &BoxedUint) -> BigUint {
878 BigUint::from_bytes_be(&value.to_be_bytes_trimmed_vartime())
879 }
880
881 fn file(key: &BIPrivateKey) -> Vec<u8> {
882 let mut out = Vec::new();
883 key.write(&mut out).unwrap();
884 out
885 }
886
887 #[test]
888 fn generated_key_is_valid() {
889 for (seed, bits) in [(1u64, 384u32), (2, 1024)] {
890 let key = seeded(seed, bits);
891 assert_eq!((key.length, key.exponent), (bits, 65537));
892 let n = bn(key.key.n().as_ref());
893 assert_eq!(n.bits(), u64::from(bits));
894 let primes = key.key.primes();
895 let (p, q) = (bn(&primes[0]), bn(&primes[1]));
896 let (d, e) = (bn(key.key.d()), BigUint::from(65537u32));
897 let one = BigUint::from(1u32);
898
899 assert_eq!(&p * &q, n);
901
902 let (p1, q1) = (&p - &one, &q - &one);
904 let phi = &p1 * &q1;
905 assert_eq!((&e * &d) % &phi, one, "e * d mod phi(n)");
906
907 assert_eq!(&d % &p1, bn(key.key.dp().unwrap()));
909 assert_eq!(&d % &q1, bn(key.key.dq().unwrap()));
910 let qinv = key.key.crt_coefficient().unwrap();
911 assert_eq!((bn(&qinv) * &q) % &p, one, "qinv * q mod p");
912
913 let bytes = file(&key);
915 let again = BIPrivateKey::read(&mut Cursor::new(&bytes)).unwrap();
916 assert_eq!(file(&again), bytes);
917 assert_eq!(again.name(), "gen");
918 }
919 }
920
921 #[test]
922 fn generated_key_signs_and_verifies() {
923 let pbo_bytes = fs::read(concat!(
924 env!("CARGO_MANIFEST_DIR"),
925 "/../../tests/fixtures/bi/sign/testsig.pbo"
926 ))
927 .unwrap();
928 let pbo = PBO::read(&mut Cursor::new(pbo_bytes)).unwrap();
929 let key = seeded(3, 1024);
930 let public = key.to_public_key().unwrap();
931 for version in [BISignVersion::V2, BISignVersion::V3] {
932 let signature = key.sign(&pbo, version).unwrap();
933 public.verify(&pbo, &signature).unwrap();
934
935 let hashes = generate_hashes(&pbo, version, 1024, false).unwrap();
937 let n = bn(key.key.n().as_ref());
938 let e = BigUint::from(65537u32);
939 for (sig, hash) in [&signature.sig1, &signature.sig2, &signature.sig3]
940 .into_iter()
941 .zip(&hashes)
942 {
943 let back = bn(sig).modpow(&e, &n);
944 assert_eq!(back.to_bytes_be(), trim_zeros(hash));
945 }
946 }
947 }
948
949 #[test]
950 fn seeded_generation_is_deterministic() {
951 assert_eq!(file(&seeded(4, 512)), file(&seeded(4, 512)));
952 assert_ne!(file(&seeded(4, 512)), file(&seeded(5, 512)));
953 }
954
955 #[test]
956 fn generation_with_the_os_rng_is_not_deterministic() {
957 let a = BIPrivateKey::generate(384, "a".to_string()).unwrap();
958 let b = BIPrivateKey::generate(384, "a".to_string()).unwrap();
959 assert_ne!(file(&a), file(&b));
960 }
961
962 #[test]
963 fn unusable_lengths_are_refused() {
964 for bits in [0, 288, 368, 383, 392, 400 + 8, MAX_KEY_BITS + 16] {
965 assert!(
966 BIPrivateKey::generate(bits, "x".to_string()).is_err(),
967 "{bits}"
968 );
969 }
970 }
971}