From a55fa4e0440500b5f99e96cd9b3d5287b5e673a4 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Sat, 30 Jul 2022 14:47:39 -0600 Subject: [PATCH] `check_public` improvements - Ensure modulus is 16384-bits or fewer. See #166 - Increase maximum public exponent. Closes #155 --- src/errors.rs | 2 ++ src/key.rs | 15 ++++++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index 2752f4c1..ead6be1a 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -15,6 +15,7 @@ pub enum Error { InvalidModulus, InvalidExponent, InvalidCoefficient, + ModulusTooLarge, PublicExponentTooSmall, PublicExponentTooLarge, Pkcs1(pkcs1::Error), @@ -41,6 +42,7 @@ impl core::fmt::Display for Error { Error::InvalidModulus => write!(f, "invalid modulus"), Error::InvalidExponent => write!(f, "invalid exponent"), Error::InvalidCoefficient => write!(f, "invalid coefficient"), + Error::ModulusTooLarge => write!(f, "modulus too large"), Error::PublicExponentTooSmall => write!(f, "public exponent too small"), Error::PublicExponentTooLarge => write!(f, "public exponent too large"), Error::Pkcs1(err) => write!(f, "{}", err), diff --git a/src/key.rs b/src/key.rs index 3b323c0b..fe3a3446 100644 --- a/src/key.rs +++ b/src/key.rs @@ -16,8 +16,9 @@ use crate::padding::PaddingScheme; use crate::raw::{DecryptionPrimitive, EncryptionPrimitive}; use crate::{oaep, pkcs1v15, pss}; -static MIN_PUB_EXPONENT: u64 = 2; -static MAX_PUB_EXPONENT: u64 = 1 << (31 - 1); +const MIN_PUB_EXPONENT: u64 = 2; +const MAX_PUB_EXPONENT: u64 = (1 << 33) - 1; +const MAX_MODULUS_BITS: usize = 16384; pub trait PublicKeyParts { /// Returns the modulus of the key. @@ -548,16 +549,20 @@ impl RsaPrivateKey { /// Check that the public key is well formed and has an exponent within acceptable bounds. #[inline] pub fn check_public(public_key: &impl PublicKeyParts) -> Result<()> { - let public_key = public_key + if public_key.n().bits() > MAX_MODULUS_BITS { + return Err(Error::ModulusTooLarge); + } + + let e = public_key .e() .to_u64() .ok_or(Error::PublicExponentTooLarge)?; - if public_key < MIN_PUB_EXPONENT { + if e < MIN_PUB_EXPONENT { return Err(Error::PublicExponentTooSmall); } - if public_key > MAX_PUB_EXPONENT { + if e > MAX_PUB_EXPONENT { return Err(Error::PublicExponentTooLarge); }