我试图像在python中一样将md5哈希值转换为long


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



当我消化“ abc”时,得到(以十六进制表示):“ 0X900150983CD24FB0D6963F7D28E17F72”

用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);
}

最佳答案

首先,让我们采用一个好的十六进制编码器,例如this answermaybeWeCouldStealAVan中的那个

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);
}


然后使用MessageDigestBigInteger(任意精度整数类型,这是您的python代码使用的类型)

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();
    }
}


我得到

191415658344158766168031473277922803570


另外,如果你这样做

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


我也明白

900150983cd24fb0d6963f7d28e17f72

10-07 13:20
查看更多