From f5d7a051a13ff6b16d69b80f91a06d264c0cd978 Mon Sep 17 00:00:00 2001 From: khai96_ Date: Tue, 23 Apr 2019 23:12:03 +0700 Subject: Convert hex strings to raw byte vectors and compare them --- src/auth.rs | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) (limited to 'src/auth.rs') diff --git a/src/auth.rs b/src/auth.rs index fed3732..806bdb7 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -20,8 +20,8 @@ pub struct BasicAuthParams { #[derive(Clone, Debug, PartialEq)] pub enum RequiredAuthPassword { Plain(String), - Sha256(String), - Sha512(String), + Sha256(Vec), + Sha512(Vec), } #[derive(Clone, Debug, PartialEq)] @@ -61,14 +61,14 @@ pub fn match_auth(basic_auth: BasicAuthParams, required_auth: &RequiredAuth) -> } } -pub fn compare_hash(password: String, hash: &String) -> bool { - get_hash_hex::(password) == *hash +pub fn compare_hash(password: String, hash: &Vec) -> bool { + get_hash::(password) == *hash } -pub fn get_hash_hex(text: String) -> String { +pub fn get_hash(text: String) -> Vec { let mut hasher = T::new(); hasher.input(text); - hex::encode(hasher.result()) + hasher.result().to_vec() } impl Middleware for Auth { @@ -110,18 +110,23 @@ impl Middleware for Auth { mod tests { use super::*; + fn assert_hex_eq(expectation: &str, received: Vec) { + let bin = hex::decode(expectation).expect("Provided string is not a valid hex code"); + assert_eq!(bin, received); + } + #[test] fn get_hash_hex_sha256() { - let expectation = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad".to_owned(); - let received = get_hash_hex::("abc".to_owned()); - assert_eq!(expectation, received); + let expectation = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + let received = get_hash::("abc".to_owned()); + assert_hex_eq(expectation, received); } #[test] fn get_hash_hex_sha512() { - let expectation = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f".to_owned(); - let received = get_hash_hex::("abc".to_owned()); - assert_eq!(expectation, received); + let expectation = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"; + let received = get_hash::("abc".to_owned()); + assert_hex_eq(expectation, received); } fn create_auth_params(username: &str, password: &str) -> BasicAuthParams { @@ -138,8 +143,8 @@ mod tests { username: username.to_owned(), password: match encrypt { "plain" => Plain(password.to_owned()), - "sha256" => Sha256(get_hash_hex::(password.to_owned())), - "sha512" => Sha512(get_hash_hex::(password.to_owned())), + "sha256" => Sha256(get_hash::(password.to_owned())), + "sha512" => Sha512(get_hash::(password.to_owned())), _ => panic!("Unknown encryption type") }, } -- cgit v1.2.3