我遇到了Java md5散列函数没有返回正确值的问题。对于大多数值,它确实返回正确的值,但是我找到了一个输出错误输出的示例。
我的代码是:
public String hash(String pass) throws Exception
{
encr = MessageDigest.getInstance("MD5");
return new BigInteger(1, encr.digest(pass.getBytes())).toString(16);
}
这会返回我尝试的大多数示例的正确答案,例如hash(“beep”) - > “1284e53a168a5ad955485a7c83b10de0”,hash(“hello”) - > “5d41402abc4b2a76b9719d911017c592”等......
然后问题出现了:hash(“dog”) - > “6d80eb0c50b49a509b49f2424e8c805”而不是“06d80eb0c50b49a509b49f2424e8c805”,这是我从几个在线md5生成器以及psql md5生成器(我的鳕鱼正在与之交互)中获得的。
我非常感谢任何人可以解决的任何问题, 感谢。
答案 0 :(得分:5)
默认情况下,它不包含前导零,但您可以自行轻松填充:
String md5 = new BigInteger(1, encr.digest(pass.getBytes())).toString(16);
return String.format("%32s", md5).replace(' ', '0');
答案 1 :(得分:0)
// I had the issue that the hash from API was not generating right.
// Using eclipse it was working correctly but when running the same API as the service runnable jar was causing wrong value to produce.
// it was caused by java as Java take Lower case and upper case letters as different Ascii values and window take them as same, so you need to simply add lower and upper case letters in your bytes to hex convertion.
// I hope this helps everyone.
private static String makeHash(String key_to_hash) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.reset();
md.update(key_to_hash.getBytes(Charset.forName("UTF-8")));
return bytesToHex(md.digest());
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static String bytesToHex(byte[] b) {
char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f','A', 'B', 'C', 'D', 'E', 'F' };
StringBuffer buf = new StringBuffer();
for (int j = 0; j < b.length; j++) {
buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]);
}
return buf.toString();
}