1

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);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
sse
  • 1,151
  • 2
  • 14
  • 26

1 Answers1

6

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
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 1
    What's the point of `new BigInteger(xxx, 16).toString(16)`? It's the same as `xxx`, i.e. that last piece of code should be just `System.out.println(bytesToHex(md5hex));` – Andreas Jun 05 '17 at 02:59
  • @Andreas Good catch. I was trying to replicate OP's value(s). – Elliott Frisch Jun 05 '17 at 03:01