From a01fd584fcc4cb5acd0efe7b7227083ede455156 Mon Sep 17 00:00:00 2001 From: _N0x Date: Thu, 31 Oct 2024 22:35:05 +0100 Subject: [PATCH] Cleaned up message padding function (thx @roh) --- src/sha/mod.rs | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/src/sha/mod.rs b/src/sha/mod.rs index 6435940..66c0d42 100644 --- a/src/sha/mod.rs +++ b/src/sha/mod.rs @@ -29,32 +29,28 @@ fn ssig1(x: u32) -> u32 { return ret; } -fn pad_message(message: String) -> Vec { - let mut msg_bytes = message.as_bytes().to_vec(); - let l = (msg_bytes.len() as u64) * 8; +fn pad_message(msg: String) -> Vec { + let l = (msg.len() as u64) << 3; + let k = ((448u64.wrapping_sub((l + 8) % 512) % 512) >> 3) as usize; - msg_bytes.push(0x80); + let mut result_u8 = Vec::with_capacity(msg.len() + 1 + k + std::mem::size_of::()); - let k = (448u64.wrapping_sub((l + 8) % 512)) % 512; - let k_bytes = k / 8; + result_u8.extend(msg.as_bytes()); + result_u8.push(0x80); + result_u8.resize(result_u8.len() + k, 0u8); + result_u8.extend(&l.to_be_bytes()); - let padding = vec![0u8; k_bytes as usize]; + let mut result_u32 = Vec::with_capacity(result_u8.len() / 4); // Allocate the right size for u32 vector - msg_bytes.extend(padding); - - msg_bytes.extend(&l.to_be_bytes()); - - let mut u32_vec = Vec::with_capacity(msg_bytes.len() / 4); // Allocate the right size for u32 vector - - for chunk in msg_bytes.chunks(4) { + for chunk in result_u8.chunks(4) { let value = (chunk[0] as u32) << 24 | (chunk[1] as u32) << 16 | (chunk[2] as u32) << 8 | (chunk[3] as u32); - u32_vec.push(value); + result_u32.push(value); } - return u32_vec; + return result_u32; } //////////// END HELPER FUNCTIONS /////////////