Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle odd keys #459

Merged
merged 2 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/algorithms/pkcs1v15.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub(crate) fn pkcs1v15_encrypt_pad<R>(
where
R: CryptoRngCore + ?Sized,
{
if msg.len() > k - 11 {
if msg.len() + 11 > k {
return Err(Error::MessageTooLong);
}

Expand Down Expand Up @@ -195,4 +195,13 @@ mod tests {
}
}
}

#[test]
fn test_encrypt_tiny_no_crash() {
let mut rng = ChaCha8Rng::from_seed([42; 32]);
let k = 8;
let message = vec![1u8; 4];
let res = pkcs1v15_encrypt_pad(&mut rng, &message, k);
assert_eq!(res, Err(Error::MessageTooLong));
}
}
14 changes: 5 additions & 9 deletions src/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,6 @@ impl RsaPrivateKey {
d: BigUint,
mut primes: Vec<BigUint>,
) -> Result<RsaPrivateKey> {
let mut should_validate = false;
if primes.len() < 2 {
if !primes.is_empty() {
return Err(Error::NprimesTooSmall);
Expand All @@ -262,7 +261,6 @@ impl RsaPrivateKey {
let (p, q) = recover_primes(&n, &e, &d)?;
primes.push(p);
primes.push(q);
should_validate = true;
}

let mut k = RsaPrivateKey {
Expand All @@ -272,10 +270,8 @@ impl RsaPrivateKey {
precomputed: None,
};

// Validate the key if we had to recover the primes.
if should_validate {
k.validate()?;
}
// Alaways validate the key, to ensure precompute can't fail
k.validate()?;

// precompute when possible, ignore error otherwise.
let _ = k.precompute();
Expand Down Expand Up @@ -787,13 +783,13 @@ mod tests {
.unwrap(),
];

RsaPrivateKey::from_components(
let res = RsaPrivateKey::from_components(
BigUint::from_bytes_be(&n),
BigUint::from_bytes_be(&e),
BigUint::from_bytes_be(&d),
primes.iter().map(|p| BigUint::from_bytes_be(p)).collect(),
)
.unwrap();
);
assert_eq!(res, Err(Error::InvalidModulus));
}

#[test]
Expand Down