Search code examples
javamd5message-digest

converting string to md5 gives add number of digits


I am trying to convert a String to its MD5 representation with this code:

public static void main(String[] args) throws NoSuchAlgorithmException {
        String s = "oshai";
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(s.getBytes(),0,s.length());
        String md5 = new BigInteger(1,m.digest()).toString(16);
        System.out.println(md5.length());
}

The returned String has add number of digits (31, so it can be an Hex number). What am I doing wrong?


Solution

  • You don't want to use BigInteger. Try a more traditional toHexString method..

    public static void main(String[] args) throws NoSuchAlgorithmException {
            String s = "oshai";
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(s.getBytes(),0,s.length());
            String string = toHexString(m.digest());
            System.out.println(string);
    }
    
    public static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for(byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }