Return None if len is wrong for alg in PublicKey::from_vec

The docstring says this is the intended behavior. The only way a `Vec<u8>`
shouldn't be simply parsed into a `PublicKey` is if it's length is not as
expected for the `algorithm` specified.
This commit is contained in:
Noah Vesely
2018-03-17 21:37:33 -06:00
committed by Romain Ruetschi
parent 2dcc46205f
commit 86bc30fe56
2 changed files with 15 additions and 0 deletions

View File

@ -88,6 +88,9 @@ impl PublicKey {
pub fn from_vec(vec: Vec<u8>, algorithm: &'static Algorithm) -> Option<PublicKey> { pub fn from_vec(vec: Vec<u8>, algorithm: &'static Algorithm) -> Option<PublicKey> {
let size = vec.len(); let size = vec.len();
let hash_output_size = algorithm.output_len; let hash_output_size = algorithm.output_len;
if size != (hash_output_size * hash_output_size * 8 * 2) {
return None;
}
let mut zero_values_merged = vec; let mut zero_values_merged = vec;
let one_values_merged = zero_values_merged.split_off(size / 2); let one_values_merged = zero_values_merged.split_off(size / 2);

View File

@ -65,6 +65,18 @@ fn test_serialization() {
assert_eq!(pub_key.zero_values, recovered_pub_key.zero_values); assert_eq!(pub_key.zero_values, recovered_pub_key.zero_values);
} }
fn test_serialization_wrong_size_key() {
let pub_key = PrivateKey::new(digest_512).public_key();
let mut too_short = pub_key.to_bytes();
let extra = too_short.pop();
assert!(PublicKey::from_vec(too_short, digest_512).is_none());
let pub_key = PrivateKey::new(digest_512).public_key();
let mut too_long = pub_key.to_bytes();
too_long.extend(extra);
assert!(PublicKey::from_vec(too_long, digest_512).is_none());
}
#[test] #[test]
#[should_panic] #[should_panic]
fn test_serialization_panic() { fn test_serialization_panic() {