The H2 HASH
function returns bytes, and SELECT HASH('MD5', 'test') AS new_id FROM my_table;
displays a text value:
098f6bcd4621d373cade4e832627b4f6
How to retrieve that same text value in Java? Using ResultSet.getBytes("new_id")
gives the object’s address, something like [B@48f278eb
. Feeding that through new String(ResultSet.getBytes("new_id"), StandardCharsets.UTF_8)
gives gobbledygook: �Oh�؆nr�Mz��
.
Advertisement
Answer
The reason you see [B@48f278eb
is because the resulting MD5 hash is in bytes in a non-string format.
Here is a complete example of generating the MD5 hash and converting the resulting bytes to a string by using a StringBuilder and formatting it String.format("%02x", b)
:
String text = "test"; //Generate MD5 hash byte[] bytesOfMessage = text.getBytes("UTF-8"); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] arr = md.digest(bytesOfMessage); //Convert the bytes to a string StringBuilder strBuilder = new StringBuilder(); for(byte b:arr){ strBuilder.append(String.format("%02x", b)); } //The complete string String strHash = strBuilder.toString(); //Print or use the string System.out.println("The MD of " + text + " is " + strHash);
And the output is as expected:
The MD of test is 098f6bcd4621d373cade4e832627b4f6