Skip to content

Commit 9956b8f

Browse files
fix: handle odd keys (#459)
Ther are two issues with oddly formed keys that were not properly handled - avoid using `-` to avoid a subtraction with overflow for pkcs - always validate the key in `from_components` to avoid errors in the internal `precompute`
1 parent 811e5d0 commit 9956b8f

File tree

2 files changed

+15
-10
lines changed

2 files changed

+15
-10
lines changed

src/algorithms/pkcs1v15.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ pub(crate) fn pkcs1v15_encrypt_pad<R>(
4141
where
4242
R: CryptoRngCore + ?Sized,
4343
{
44-
if msg.len() > k - 11 {
44+
if msg.len() + 11 > k {
4545
return Err(Error::MessageTooLong);
4646
}
4747

@@ -195,4 +195,13 @@ mod tests {
195195
}
196196
}
197197
}
198+
199+
#[test]
200+
fn test_encrypt_tiny_no_crash() {
201+
let mut rng = ChaCha8Rng::from_seed([42; 32]);
202+
let k = 8;
203+
let message = vec![1u8; 4];
204+
let res = pkcs1v15_encrypt_pad(&mut rng, &message, k);
205+
assert_eq!(res, Err(Error::MessageTooLong));
206+
}
198207
}

src/key.rs

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,6 @@ impl RsaPrivateKey {
252252
d: BigUint,
253253
mut primes: Vec<BigUint>,
254254
) -> Result<RsaPrivateKey> {
255-
let mut should_validate = false;
256255
if primes.len() < 2 {
257256
if !primes.is_empty() {
258257
return Err(Error::NprimesTooSmall);
@@ -262,7 +261,6 @@ impl RsaPrivateKey {
262261
let (p, q) = recover_primes(&n, &e, &d)?;
263262
primes.push(p);
264263
primes.push(q);
265-
should_validate = true;
266264
}
267265

268266
let mut k = RsaPrivateKey {
@@ -272,10 +270,8 @@ impl RsaPrivateKey {
272270
precomputed: None,
273271
};
274272

275-
// Validate the key if we had to recover the primes.
276-
if should_validate {
277-
k.validate()?;
278-
}
273+
// Alaways validate the key, to ensure precompute can't fail
274+
k.validate()?;
279275

280276
// precompute when possible, ignore error otherwise.
281277
let _ = k.precompute();
@@ -787,13 +783,13 @@ mod tests {
787783
.unwrap(),
788784
];
789785

790-
RsaPrivateKey::from_components(
786+
let res = RsaPrivateKey::from_components(
791787
BigUint::from_bytes_be(&n),
792788
BigUint::from_bytes_be(&e),
793789
BigUint::from_bytes_be(&d),
794790
primes.iter().map(|p| BigUint::from_bytes_be(p)).collect(),
795-
)
796-
.unwrap();
791+
);
792+
assert_eq!(res, Err(Error::InvalidModulus));
797793
}
798794

799795
#[test]

0 commit comments

Comments
 (0)