1

The H2 HASH function returns bytes, and SELECT HASH('MD5', 'test') AS new_id FROM my_table; displays a text value: 098f6bcd4621d373cade4e832627b4f6 enter image description here

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��.

niemand
  • 43
  • 6
  • Does this answer your question? [How can I generate an MD5 hash in Java?](https://stackoverflow.com/questions/415953/how-can-i-generate-an-md5-hash-in-java) Note also that you are trying to generate a hash with the input "new_id", but that is just the variable name and should have nothing to do with your question, as shown in your image and your question, the text to hash is "test" which gives "098f6bcd4621d373cade4e832627b4f6" – sorifiend Mar 14 '22 at 02:07
  • The "new_id" you're referring to as variable name is the column alias I gave to the sample query just as an illustration. I have an H2 database table with a column of values that I want to generate MD5 hash for. It is a database table migrated from MySQL, whose MD5() function yields a text value such that rs.getString("new_id") works. But H2 database returns the value in bytes, which is giving me problems. I'll take a look at the link you provided and see what's there. – niemand Mar 14 '22 at 02:28

1 Answers1

0

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
sorifiend
  • 5,927
  • 1
  • 28
  • 45
  • 1
    Thanks. I know nothing about MD5 (except that it's not secure) and did not consider the possibility that the resulting hash string is in fact hex. All I knew was that I wanted that column of varchars hashed into unrecognizable strings of text that are the same value as what MySQL's MD5() function provides. – niemand Mar 14 '22 at 03:34