Skip to content

Commit

Permalink
check_public improvements (#170)
Browse files Browse the repository at this point in the history
- Ensure modulus is 16384-bits or fewer. See #166
- Increase maximum public exponent. Closes #155
  • Loading branch information
tarcieri authored Aug 7, 2022
1 parent 4ccdcf9 commit 8d3fe53
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
2 changes: 2 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub enum Error {
InvalidModulus,
InvalidExponent,
InvalidCoefficient,
ModulusTooLarge,
PublicExponentTooSmall,
PublicExponentTooLarge,
Pkcs1(pkcs1::Error),
Expand All @@ -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),
Expand Down
15 changes: 10 additions & 5 deletions src/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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);
}

Expand Down

0 comments on commit 8d3fe53

Please sign in to comment.