简体   繁体   English

如何在Java中将md5哈希转换为整数类型?

[英]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, 我想像在python中一样将md5哈希转换为long

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

When I digest "abc", I get (in Hex): "0X900150983CD24FB0D6963F7D28E17F72" 当我消化“ abc”时,得到(以十六进制表示):“ 0X900150983CD24FB0D6963F7D28E17F72”

What is the correct way to do this hash conversion in Java? 用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);
}

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) 然后使用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();
    }
}

and I get 我得到

191415658344158766168031473277922803570

Also , if you do 另外 ,如果您这样做

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

I too get 我也明白

900150983cd24fb0d6963f7d28e17f72

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM