From 0a3b9e0220bd7f766c127cf65ffc3cb1de8ab2fb Mon Sep 17 00:00:00 2001 From: Jason Ish Date: Wed, 30 Dec 2020 16:37:28 -0600 Subject: [PATCH] rust/hashing: add function to finalize md5 to hex string New function, SCMd5FinalizeToHex to finalize an md5 hash to a hex string. --- rust/src/ffi/hashing.rs | 24 ++++++++++++++++++++++++ src/rust.h | 3 +++ 2 files changed, 27 insertions(+) diff --git a/rust/src/ffi/hashing.rs b/rust/src/ffi/hashing.rs index c73606582e..7f9f09aef7 100644 --- a/rust/src/ffi/hashing.rs +++ b/rust/src/ffi/hashing.rs @@ -24,6 +24,9 @@ use std::os::raw::c_char; pub const SC_SHA1_LEN: usize = 20; pub const SC_SHA256_LEN: usize = 32; +// Length of a MD5 hex string, not including a trailing NUL. +pub const SC_MD5_HEX_LEN: usize = 32; + // Wrap the Rust Sha256 in a new type named SCSha256 to give this type // the "SC" prefix. The one drawback is we must access the actual context // with .0. @@ -147,12 +150,33 @@ pub unsafe extern "C" fn SCMd5Update(hasher: &mut SCMd5, bytes: *const u8, len: update(&mut hasher.0, bytes, len); } +/// Finalize the MD5 hash placing the digest in the provided out buffer. +/// +/// This function consumes the SCMd5 hash context. #[no_mangle] pub unsafe extern "C" fn SCMd5Finalize(hasher: &mut SCMd5, out: *mut u8, len: u32) { let hasher: Box = Box::from_raw(hasher); finalize(hasher.0, out, len); } +/// Finalize MD5 context to a hex string. +/// +/// Consumes the hash context and cannot be re-used. +#[no_mangle] +pub unsafe extern "C" fn SCMd5FinalizeToHex(hasher: &mut SCMd5, out: *mut c_char, len: u32) { + let out = &mut *(out as *mut u8); + let hasher: Box = Box::from_raw(hasher); + let result = hasher.0.finalize(); + let hex = format!("{:x}", &result); + let output = std::slice::from_raw_parts_mut(out, len as usize); + + // This will panic if the sizes differ. + output[0..len as usize - 1].copy_from_slice(&hex.as_bytes()); + + // Terminate the string. + output[output.len() - 1] = 0; +} + /// Free an unfinalized Sha1 context. #[no_mangle] pub unsafe extern "C" fn SCMd5Free(hasher: &mut SCMd5) { diff --git a/src/rust.h b/src/rust.h index 2503e89b1c..b0b94f7f41 100644 --- a/src/rust.h +++ b/src/rust.h @@ -27,6 +27,9 @@ #define SC_SHA1_LEN 20 #define SC_SHA256_LEN 32 +/* Length of an MD5 hex string, not including a trailing NUL. */ +#define SC_MD5_HEX_LEN 32 + #define JB_SET_STRING(jb, key, val) jb_set_formatted((jb), "\"" key "\":\"" val "\"") #define JB_SET_TRUE(jb, key) jb_set_formatted((jb), "\"" key "\":true") #define JB_SET_FALSE(jb, key) jb_set_formatted((jb), "\"" key "\":false")