From 14c177905608f98eb528fae3a66debc3592c79d3 Mon Sep 17 00:00:00 2001 From: johannesd3 Date: Wed, 26 May 2021 20:45:22 +0200 Subject: [PATCH] Adjust arg types of `Credentials::with_blob` ... to avoid redundant utf-8 checking --- core/src/authentication.rs | 16 +++++++++++----- discovery/src/server.rs | 5 ++--- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/core/src/authentication.rs b/core/src/authentication.rs index db787bbe..3c188ecf 100644 --- a/core/src/authentication.rs +++ b/core/src/authentication.rs @@ -42,7 +42,11 @@ impl Credentials { } } - pub fn with_blob(username: String, encrypted_blob: &str, device_id: &str) -> Credentials { + pub fn with_blob( + username: impl Into, + encrypted_blob: impl AsRef<[u8]>, + device_id: impl AsRef<[u8]>, + ) -> Credentials { fn read_u8(stream: &mut R) -> io::Result { let mut data = [0u8]; stream.read_exact(&mut data)?; @@ -67,7 +71,9 @@ impl Credentials { Ok(data) } - let secret = Sha1::digest(device_id.as_bytes()); + let username = username.into(); + + let secret = Sha1::digest(device_id.as_ref()); let key = { let mut key = [0u8; 24]; @@ -88,9 +94,9 @@ impl Credentials { let mut data = base64::decode(encrypted_blob).unwrap(); let cipher = Aes192::new(GenericArray::from_slice(&key)); let block_size = ::BlockSize::to_usize(); + assert_eq!(data.len() % block_size, 0); - // replace to chunks_exact_mut with MSRV bump to 1.31 - for chunk in data.chunks_mut(block_size) { + for chunk in data.chunks_exact_mut(block_size) { cipher.decrypt_block(GenericArray::from_mut_slice(chunk)); } @@ -102,7 +108,7 @@ impl Credentials { data }; - let mut cursor = io::Cursor::new(&blob); + let mut cursor = io::Cursor::new(blob.as_slice()); read_u8(&mut cursor).unwrap(); read_bytes(&mut cursor).unwrap(); read_u8(&mut cursor).unwrap(); diff --git a/discovery/src/server.rs b/discovery/src/server.rs index 53b849f7..57f5bf46 100644 --- a/discovery/src/server.rs +++ b/discovery/src/server.rs @@ -129,11 +129,10 @@ impl RequestHandler { GenericArray::from_slice(iv), ); cipher.apply_keystream(&mut data); - String::from_utf8(data).unwrap() + data }; - let credentials = - Credentials::with_blob(username.to_string(), &decrypted, &self.config.device_id); + let credentials = Credentials::with_blob(username, &decrypted, &self.config.device_id); self.tx.send(credentials).unwrap();