From bf5d2d6d6bc6aa0848a44e2c0e13df5e4ffdf8b5 Mon Sep 17 00:00:00 2001 From: Avril Date: Sun, 21 Mar 2021 19:05:07 +0000 Subject: [PATCH] fix panic on invalid key sizes --- Cargo.lock | 2 +- src/key.rs | 6 ++++-- src/main.rs | 7 ++++--- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c07f44c..8645a9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -34,7 +34,7 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chacha20" -version = "0.1.0" +version = "1.0.0" dependencies = [ "base64", "getrandom", diff --git a/src/key.rs b/src/key.rs index a9920f7..a7d8b93 100644 --- a/src/key.rs +++ b/src/key.rs @@ -131,7 +131,8 @@ impl str::FromStr for Key base64::decode_config_buf(s.as_bytes(), base64::STANDARD, &mut buffer)?; let mut this = Self::default(); - this.0.copy_from_slice(&buffer[..]); + let sz = std::cmp::min(KEY_SIZE, buffer.len()); + this.0.copy_from_slice(&buffer[..sz]); Ok(this) } } @@ -145,7 +146,8 @@ impl str::FromStr for IV base64::decode_config_buf(s.as_bytes(), base64::STANDARD, &mut buffer)?; let mut this = Self::default(); - this.0.copy_from_slice(&buffer[..]); + let sz = std::cmp::min(IV_SIZE, buffer.len()); + this.0.copy_from_slice(&buffer[..sz]); Ok(this) } } diff --git a/src/main.rs b/src/main.rs index 4638241..cd02001 100644 --- a/src/main.rs +++ b/src/main.rs @@ -41,9 +41,10 @@ fn keys() -> Result<(Mode, Key, IV), base64::DecodeError> eprintln!("Usage: {} decrypt [] []", prog_name); eprintln!("Usage: {} keygen", prog_name); eprintln!(); - eprintln!("(Key size is {}, IV size is {})\n", cha::KEY_SIZE, cha::IV_SIZE); - eprintln!("encrypt/decrypt:\n\tIf key and/or IV are not provided, they are generated randomly and printed to stderr in order on one line each"); - eprintln!("keygen:\n\tThe key/iv is printed in the same way as auto-generated keys for the en/decryption modes, but to stdout instead of stderr"); + eprintln!("(Key size is {}, IV size is {})", cha::KEY_SIZE, cha::IV_SIZE); + eprintln!("\nencrypt/decrypt:\n\tIf key and/or IV are not provided, they are generated randomly and printed to stderr in order on one line each"); + eprintln!("\tIf the key and/or IV provided's size is lower than the cipher's key/IV size, the rest of the key/IV padded with 0s. If the size is higher, the extra bytes are ignored."); + eprintln!("\nkeygen:\n\tThe key/iv is printed in the same way as auto-generated keys for the en/decryption modes, but to stdout instead of stderr"); std::process::exit(1) } };