From 86bc30fe563cbcfb9be4cba36eb245812331779b Mon Sep 17 00:00:00 2001 From: Noah Vesely Date: Sat, 17 Mar 2018 21:37:33 -0600 Subject: [PATCH] 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` shouldn't be simply parsed into a `PublicKey` is if it's length is not as expected for the `algorithm` specified. --- src/lib.rs | 3 +++ src/tests.rs | 12 ++++++++++++ 2 files changed, 15 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 4b3a2a4..63e6edd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -88,6 +88,9 @@ impl PublicKey { pub fn from_vec(vec: Vec, algorithm: &'static Algorithm) -> Option { let size = vec.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 one_values_merged = zero_values_merged.split_off(size / 2); diff --git a/src/tests.rs b/src/tests.rs index d41fd3e..26505b1 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -65,6 +65,18 @@ fn test_serialization() { 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] #[should_panic] fn test_serialization_panic() {