Skip to content

Commit 643c78f

Browse files
committed
ssh-key: simplified ECDSA private key decoding logic
Followup to #351
1 parent bf080c9 commit 643c78f

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed

ssh-key/src/private/ecdsa.rs

+12-13
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Elliptic Curve Digital Signature Algorithm (ECDSA) private keys.
22
3-
use crate::{Algorithm, EcdsaCurve, Error, Result, public::EcdsaPublicKey};
3+
use crate::{public::EcdsaPublicKey, Algorithm, EcdsaCurve, Error, Result};
44
use core::fmt;
55
use encoding::{CheckedSum, Decode, Encode, Reader, Writer};
66
use sec1::consts::{U32, U48, U66};
@@ -39,27 +39,26 @@ impl<const SIZE: usize> Decode for EcdsaPrivateKey<SIZE> {
3939

4040
fn decode(reader: &mut impl Reader) -> Result<Self> {
4141
reader.read_prefixed(|reader| {
42-
let len = reader.remaining_len();
42+
let mut len = reader.remaining_len();
43+
4344
if len == SIZE.checked_add(1).ok_or(encoding::Error::Length)? {
4445
// Strip leading zero
4546
// TODO(tarcieri): make sure leading zero was necessary
4647
if u8::decode(reader)? != 0 {
4748
return Err(Error::FormatEncoding);
4849
}
50+
51+
len -= 1;
4952
}
5053

51-
let mut bytes = [0u8; SIZE];
52-
if SIZE == 66 {
53-
// https://stackoverflow.com/questions/50002149/why-p-521-public-key-x-y-some-time-is-65-bytes-some-time-is-66-bytes
54-
// although lower keys than 64 are vanishingly possible, but lets stop here
55-
if len > 63 {
56-
reader.read(&mut bytes[..core::cmp::min(len, SIZE)])?;
57-
} else {
58-
return Err(encoding::Error::Length.into());
59-
}
60-
} else {
61-
reader.read(&mut bytes)?;
54+
// Minimum allowed key size: may be smaller than modulus size
55+
const MIN_SIZE: usize = 32;
56+
if len < MIN_SIZE || len > SIZE {
57+
return Err(encoding::Error::Length.into());
6258
}
59+
60+
let mut bytes = [0u8; SIZE];
61+
reader.read(&mut bytes[..len])?;
6362
Ok(Self { bytes })
6463
})
6564
}

0 commit comments

Comments
 (0)