rsa: Replace use of SmallerModulus with dynamic checks.

The dynamic checks should never fail but since they are added in
already-fallible functions they won't cause any trouble. This
facilitates future changes where the dynmic checks are required.
This commit is contained in:
Brian Smith 2023-11-22 19:00:14 -08:00
parent ae02e961cf
commit 1855573098
2 changed files with 19 additions and 10 deletions

View File

@ -12,7 +12,7 @@
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use super::{super::n0::N0, BoxedLimbs, Elem, PublicModulus, SmallerModulus, Unencoded};
use super::{super::n0::N0, BoxedLimbs, Elem, PublicModulus, Unencoded};
use crate::{
bits::BitLength,
cpu, error,
@ -146,16 +146,19 @@ impl<M> OwnedModulus<M> {
})
}
pub fn to_elem<L>(&self, l: &Modulus<L>) -> Elem<L, Unencoded>
where
M: SmallerModulus<L>,
{
pub fn to_elem<L>(&self, l: &Modulus<L>) -> Result<Elem<L, Unencoded>, error::Unspecified> {
if self.len_bits() > l.len_bits()
|| (self.limbs.len() == l.limbs().len()
&& limb::limbs_less_than_limbs_consttime(&self.limbs, l.limbs()) != LimbMask::True)
{
return Err(error::Unspecified);
}
let mut limbs = BoxedLimbs::zero(l.limbs.len());
limbs[..self.limbs.len()].copy_from_slice(&self.limbs);
Elem {
Ok(Elem {
limbs,
encoding: PhantomData,
}
})
}
pub fn modulus(&self) -> Modulus<M> {
Modulus {

View File

@ -317,8 +317,14 @@ impl KeyPair {
// 0 < q < p < n. We check that q and p are close to sqrt(n) and then
// assume that these preconditions are enough to let us assume that
// checking p * q == 0 (mod n) is equivalent to checking p * q == n.
let q_mod_n = q.modulus.to_elem(n);
let p_mod_n = p.modulus.to_elem(n);
let q_mod_n = q
.modulus
.to_elem(n)
.map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
let p_mod_n = p
.modulus
.to_elem(n)
.map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
let p_mod_n = bigint::elem_mul(n_one, p_mod_n, n);
let pq_mod_n = bigint::elem_mul(&q_mod_n, p_mod_n, n);
if !pq_mod_n.is_zero() {
@ -586,7 +592,7 @@ impl KeyPair {
// Modular arithmetic is used simply to avoid implementing
// non-modular arithmetic.
let h = bigint::elem_widen(h, n);
let q_mod_n = self.q.modulus.to_elem(n);
let q_mod_n = self.q.modulus.to_elem(n)?;
let q_mod_n = bigint::elem_mul(n_one, q_mod_n, n);
let q_times_h = bigint::elem_mul(&q_mod_n, h, n);
let m_2 = bigint::elem_widen(m_2, n);