Skip to content

Commit

Permalink
Merge pull request #33145 from vespa-engine/hakonhall/add-hex-formatt…
Browse files Browse the repository at this point in the history
…ing-of-md5-hash

Add hex formatting of MD5 hash
  • Loading branch information
freva authored Jan 21, 2025
2 parents 3c2b685 + deb8c0c commit 85260d8
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions vespajlib/abi-spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -3343,6 +3343,7 @@
],
"methods" : [
"public void <init>()",
"public static java.lang.String toHex(byte[])",
"public static java.lang.String escape(java.lang.String)",
"public static java.lang.String escape(java.lang.String, char)",
"public static java.lang.String unescape(java.lang.String)",
Expand Down
6 changes: 6 additions & 0 deletions vespajlib/src/main/java/com/yahoo/collections/MD5.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.collections;

import com.yahoo.text.StringUtilities;
import com.yahoo.text.Utf8;

import java.security.MessageDigest;
Expand Down Expand Up @@ -69,4 +70,9 @@ public byte[] hashFull(String s) {
return digester.digest(Utf8.toBytes(s));
}

/** Returns the 32 byte representation of the MD5 hash of the given string. Compatible with md5sum(1). */
public String hashToHex(String s) {
return StringUtilities.toHex(hashFull(s));
}

}
10 changes: 10 additions & 0 deletions vespajlib/src/main/java/com/yahoo/text/StringUtilities.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ public class StringUtilities {

private static byte toHex(int val) { return (byte) (val < 10 ? '0' + val : 'a' + (val - 10)); }

/** Returns a String where each byte b in `bytes` is replaced by "%02x".formatted(b). */
public static String toHex(byte[] bytes) {
byte[] encoded = new byte[bytes.length * 2];
for (int i = 0; i < bytes.length; i++) {
encoded[i * 2] = toHex((bytes[i] >> 4) & 0xF);
encoded[i * 2 + 1] = toHex(bytes[i] & 0xF);
}
return new String(encoded, StandardCharsets.US_ASCII);
}

private static class ReplacementCharacters {

public byte[] needEscape = new byte[256];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@
*/
public class MD5TestCase {

@Test
public void testHashToHex() {
MD5 md5 = new MD5();
// Matches output from `md5sum <<< hello`
assertEquals("b1946ac92492d2347c6235b4d2611184", md5.hashToHex("hello\n"));
}

@Test
public void testMD5() {
MD5 md5 = new MD5();
Expand Down

0 comments on commit 85260d8

Please sign in to comment.