MD5 hash on modern java

To get a similar php md5 or postgresql md5 function on java then try this code.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {

public static String byteArrayToHex(byte[] a) {
       StringBuilder sb = new StringBuilder(a.length * 2);
       for(byte b: a)
          sb.append(String.format("%02x", b));
       return sb.toString();
}

public static String Hash(String input) throws NoSuchAlgorithmException {

    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(input.getBytes());
    byte[] digest = md.digest();
    return byteArrayToHex(digest);
}

}

Leave a Reply

Your email address will not be published. Required fields are marked *