From b795c22f60a20b1ccd92e212b8697bd02289de61 Mon Sep 17 00:00:00 2001 From: dignifiedquire Date: Thu, 30 Nov 2023 22:44:47 +0100 Subject: [PATCH] cache p and q params --- src/algorithms/rsa.rs | 8 +++----- src/key.rs | 16 ++++++++++++++++ src/traits/keys.rs | 4 ++++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/algorithms/rsa.rs b/src/algorithms/rsa.rs index b52754b6..b24fc042 100644 --- a/src/algorithms/rsa.rs +++ b/src/algorithms/rsa.rs @@ -79,21 +79,19 @@ pub fn rsa_decrypt( let dp = priv_key.dp().unwrap(); let dq = priv_key.dq().unwrap(); let qinv = priv_key.qinv().unwrap(); + let p_params = priv_key.p_params().unwrap(); + let q_params = priv_key.q_params().unwrap(); let p = &priv_key.primes()[0]; let q = &priv_key.primes()[1]; - // TODO: store - let p_params = BoxedResidueParams::new(p.clone()).unwrap(); - let q_params = BoxedResidueParams::new(q.clone()).unwrap(); - // precomputed: dP = (1/e) mod (p-1) = d mod (p-1) // precomputed: dQ = (1/e) mod (q-1) = d mod (q-1) // m1 = c^dP mod p let m1 = pow_mod_params(&c, &dp, p_params.clone()); // m2 = c^dQ mod q - let m2 = pow_mod_params(&c, &dq, q_params); + let m2 = pow_mod_params(&c, &dq, q_params.clone()); // precomputed: qInv = (1/q) mod p diff --git a/src/key.rs b/src/key.rs index a8e8bf34..452d6954 100644 --- a/src/key.rs +++ b/src/key.rs @@ -104,6 +104,9 @@ pub(crate) struct PrecomputedValues { pub(crate) qinv: BoxedUint, pub(crate) residue_params: BoxedResidueParams, + + pub(crate) p_params: BoxedResidueParams, + pub(crate) q_params: BoxedResidueParams, } impl Zeroize for PrecomputedValues { @@ -404,11 +407,16 @@ impl RsaPrivateKey { let residue_params = BoxedResidueParams::new(self.pubkey_components.n.clone().get()).unwrap(); + let p_params = BoxedResidueParams::new(p.clone()).unwrap(); + let q_params = BoxedResidueParams::new(q.clone()).unwrap(); + self.precomputed = Some(PrecomputedValues { dp, dq, qinv, residue_params, + p_params, + q_params, }); Ok(()) @@ -535,6 +543,14 @@ impl PrivateKeyPartsNew for RsaPrivateKey { fn residue_params(&self) -> Option<&BoxedResidueParams> { self.precomputed.as_ref().map(|p| &p.residue_params) } + + fn p_params(&self) -> Option<&BoxedResidueParams> { + self.precomputed.as_ref().map(|p| &p.p_params) + } + + fn q_params(&self) -> Option<&BoxedResidueParams> { + self.precomputed.as_ref().map(|p| &p.q_params) + } } /// Check that the public key is well formed and has an exponent within acceptable bounds. diff --git a/src/traits/keys.rs b/src/traits/keys.rs index 11985856..5912ed01 100644 --- a/src/traits/keys.rs +++ b/src/traits/keys.rs @@ -120,6 +120,10 @@ pub trait PrivateKeyPartsNew: PublicKeyPartsNew { fn crt_values(&self) -> Option<&[CrtValueNew]>; fn residue_params(&self) -> Option<&BoxedResidueParams>; + + fn p_params(&self) -> Option<&BoxedResidueParams>; + + fn q_params(&self) -> Option<&BoxedResidueParams>; } /// Contains the precomputed Chinese remainder theorem values.