Skip to content

Commit

Permalink
fix: always validate keys in from_components
Browse files Browse the repository at this point in the history
Otherwise the inner precompute could fail
  • Loading branch information
dignifiedquire committed Nov 18, 2024
1 parent 201ad81 commit 2edd479
Showing 1 changed file with 5 additions and 9 deletions.
14 changes: 5 additions & 9 deletions src/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,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 @@ -261,7 +260,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 @@ -271,10 +269,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 @@ -717,13 +713,13 @@ mod tests {
Base64::decode_vec("CUWC+hRWOT421kwRllgVjy6FYv6jQUcgDNHeAiYZnf5HjS9iK2ki7v8G5dL/0f+Yf+NhE/4q8w4m8go51hACrVpP1p8GJDjiT09+RsOzITsHwl+ceEKoe56ZW6iDHBLlrNw5/MtcYhKpjNU9KJ2udm5J/c9iislcjgckrZG2IB8ADgXHMEByZ5DgaMl4AKZ1Gx8/q6KftTvmOT5rNTMLi76VN5KWQcDWK/DqXiOiZHM7Nr4dX4me3XeRgABJyNR8Fqxj3N1+HrYLe/zs7LOaK0++F9Ul3tLelhrhsvLxei3oCZkF9A/foD3on3luYA+1cRcxWpSY3h2J4/22+yo4+Q==").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

0 comments on commit 2edd479

Please sign in to comment.