sad_rsa/traits/
keys.rs

1//! Traits related to the key components
2
3use alloc::boxed::Box;
4use crypto_bigint::{
5    modular::{BoxedMontyForm, BoxedMontyParams},
6    BoxedUint, NonZero,
7};
8use zeroize::Zeroize;
9
10/// Components of an RSA public key.
11pub trait PublicKeyParts {
12    /// Returns the modulus of the key.
13    fn n(&self) -> &NonZero<BoxedUint>;
14
15    /// Returns the public exponent of the key.
16    fn e(&self) -> &BoxedUint;
17
18    /// Returns the modulus size in bytes. Raw signatures and ciphertexts for
19    /// or by this public key will have the same size.
20    fn size(&self) -> usize {
21        (self.n().bits() as usize).div_ceil(8)
22    }
23
24    /// Returns the parameters for montgomery operations.
25    fn n_params(&self) -> &BoxedMontyParams;
26
27    /// Returns precision (in bits) of `n`.
28    fn n_bits_precision(&self) -> u32 {
29        self.n().bits_precision()
30    }
31
32    /// Returns the big endian serialization of the modulus of the key
33    fn n_bytes(&self) -> Box<[u8]> {
34        self.n().to_be_bytes_trimmed_vartime()
35    }
36
37    /// Returns the big endian serialization of the public exponent of the key
38    fn e_bytes(&self) -> Box<[u8]> {
39        self.e().to_be_bytes_trimmed_vartime()
40    }
41}
42
43/// Components of an RSA private key.
44pub trait PrivateKeyParts: PublicKeyParts {
45    /// Returns the private exponent of the key.
46    fn d(&self) -> &BoxedUint;
47
48    /// Returns the prime factors.
49    fn primes(&self) -> &[BoxedUint];
50
51    /// Returns the precomputed dp value, D mod (P-1)
52    fn dp(&self) -> Option<&BoxedUint>;
53
54    /// Returns the precomputed dq value, D mod (Q-1)
55    fn dq(&self) -> Option<&BoxedUint>;
56
57    /// Returns the precomputed qinv value, Q^-1 mod P
58    fn qinv(&self) -> Option<&BoxedMontyForm>;
59
60    /// Returns an iterator over the CRT Values
61    fn crt_values(&self) -> Option<&[CrtValue]>;
62
63    /// Returns the params for `p` if precomputed.
64    fn p_params(&self) -> Option<&BoxedMontyParams>;
65
66    /// Returns the params for `q` if precomputed.
67    fn q_params(&self) -> Option<&BoxedMontyParams>;
68}
69
70/// Contains the precomputed Chinese remainder theorem values.
71#[derive(Debug, Clone)]
72pub struct CrtValue {
73    /// D mod (prime - 1)
74    pub(crate) exp: BoxedUint,
75    /// R·Coeff ≡ 1 mod Prime.
76    pub(crate) coeff: BoxedUint,
77    /// product of primes prior to this (inc p and q)
78    pub(crate) r: BoxedUint,
79}
80
81impl Zeroize for CrtValue {
82    fn zeroize(&mut self) {
83        self.exp.zeroize();
84        self.coeff.zeroize();
85        self.r.zeroize();
86    }
87}
88
89impl Drop for CrtValue {
90    fn drop(&mut self) {
91        self.zeroize();
92    }
93}