[英]How can I convert a md5 hash to an integral type in Java?
我想像在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);
}
首先,让我们采用一个好十六进制编码器,就像也许来自我们可能的 答案中的那个
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);
}
然后使用MessageDigest
和BigInteger
(任意精度整数类型,这是您的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.