Skip to content

Commit 0a70ff1

Browse files
yalemandacut
authored andcommitted
fix: handle keys that are too short
1 parent 71fe831 commit 0a70ff1

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

src/error.rs

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -188,15 +188,23 @@ impl From<Box<dyn Error + Send + Sync>> for SignatureError {
188188

189189
/// Error returned by `KSecretKey::from_str` when the secret key cannot fit in the expected size.
190190
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
191-
pub struct KeyTooLongError;
191+
pub enum KeyLengthError {
192+
/// The key is too long.
193+
TooLong,
194+
/// The key is too short.
195+
TooShort,
196+
}
192197

193-
impl Display for KeyTooLongError {
198+
impl Display for KeyLengthError {
194199
fn fmt(&self, f: &mut Formatter) -> FmtResult {
195-
f.write_str("Key too long")
200+
match self {
201+
KeyLengthError::TooLong => f.write_str("Key too long"),
202+
KeyLengthError::TooShort => f.write_str("Key too short"),
203+
}
196204
}
197205
}
198206

199-
impl Error for KeyTooLongError {}
207+
impl Error for KeyLengthError {}
200208

201209
#[cfg(test)]
202210
mod tests {

src/signing_key.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use {
22
crate::{
33
crypto::{hmac_sha256, SHA256_OUTPUT_LEN},
4-
KeyTooLongError,
4+
KeyLengthError,
55
},
66
chrono::NaiveDate,
77
derive_builder::Builder,
@@ -147,13 +147,16 @@ impl Display for KSigningKey {
147147
}
148148

149149
impl<const M: usize> FromStr for KSecretKey<M> {
150-
type Err = KeyTooLongError;
150+
type Err = KeyLengthError;
151151

152152
/// Create a new `KSecretKey` from a raw AWS secret key.
153-
fn from_str(raw: &str) -> Result<Self, KeyTooLongError> {
153+
fn from_str(raw: &str) -> Result<Self, KeyLengthError> {
154154
let len = raw.len();
155155
if len > M - 4 {
156-
return Err(KeyTooLongError);
156+
return Err(KeyLengthError::TooLong);
157+
}
158+
if len + 4 < M {
159+
return Err(KeyLengthError::TooShort);
157160
}
158161

159162
let mut prefixed_key = [0; M];

0 commit comments

Comments
 (0)