]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
rust/hashing: add function to finalize md5 to hex string
authorJason Ish <jason.ish@oisf.net>
Wed, 30 Dec 2020 22:37:28 +0000 (16:37 -0600)
committerVictor Julien <victor@inliniac.net>
Wed, 13 Jan 2021 08:01:05 +0000 (09:01 +0100)
New function, SCMd5FinalizeToHex to finalize an md5 hash
to a hex string.

rust/src/ffi/hashing.rs
src/rust.h

index c73606582e54a22c048b8a2de9e860b56ef239bf..7f9f09aef76d94056fc7294cc2555b8f4cf4ddd5 100644 (file)
@@ -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<SCMd5> = 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<SCMd5> = 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) {
index 2503e89b1c8ebe0b583019c25bcf7c1189158dad..b0b94f7f41647a67ab8595f52c82f96f4fa77987 100644 (file)
@@ -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")