sse
sse

Reputation: 1151

How can I convert a md5 hash to an integral type in Java?

I am trying to convert a md5 hash to a long like I can in python,

>>> int(hashlib.md5("abc").hexdigest(),16) 
191415658344158766168031473277922803570L 

When I digest "abc", I get (in Hex): "0X900150983CD24FB0D6963F7D28E17F72"

What is the correct way to do this hash conversion in Java?

public static void main(String[] args) {
    byte[] md5hex = DigestUtils.md5("abc");
    String hex = new String(Hex.encodeHex(md5hex));
    System.out.println(hex);
    long lv = Long.parseLong("0X" + hex.toUpperCase(), 16);
    System.out.println(lv);
    int hext = Integer.parseInt("12346789", 16);
    System.out.println(hext);
}

Upvotes: 1

Views: 5111

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201507

First, let's take a good hex encoder like the one in this answer from maybeWeCouldStealAVan

private final static char[] hexArray = "0123456789ABCDEF".toCharArray();

public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

Then use MessageDigest and BigInteger (an arbitrary precision integer type, which is what your python code is using)

public static void main(String[] args) {
    try {
        byte[] md5hex = MessageDigest.getInstance("MD5").digest("abc".getBytes());
        System.out.println(new BigInteger(bytesToHex(md5hex), 16));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

and I get

191415658344158766168031473277922803570

Also, if you do

System.out.println(bytesToHex(md5hex));

I too get

900150983cd24fb0d6963f7d28e17f72

Upvotes: 6

Related Questions