我在 Android 上,所以它只是 java,我有相同的输入字符串,但每次都得到不同的值。我错过了什么?谢谢
private String getShortenedKey(String key) {
String shortenedKey=null;
MessageDigest md = null;
LogUtils.LOGD(HASH_ALGO, "before key: "+ System.currentTimeMillis());
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
shortenedKey = key;
}
LogUtils.LOGD(HASH_ALGO, "after key: "+ System.currentTimeMillis());
md.update(key.getBytes());
byte[] shortenedBytes = md.digest();
shortenedKey = String.valueOf(shortenedBytes);
return shortenedKey;
}
输入字符串:
{"config":{"wp":"(1.000000,1.000000,1.000000,1.000000)","v":"8","unit":"auto","ef":true,"ws":1,"tt":0,"cs":1},"items":[{"startTime":1409180400,"id":"WorkXYZ@habit.skedgo.com_1409180400","class":"event","endTime":1409209200,"location":{"lng":151.20785,"lat":-33.85926},"priority":0},{"startTime":1409148000,"id":"HomeXYZ@habit.skedgo.com_1409148000","class":"event","endTime":1409234340,"location":{"lng":151.18089,"lat":-33.89153},"priority":0}]}
更新:这么多有效答案,谢谢。我选择最容易改变的那个。干杯。
最佳答案
这一行
shortenedKey = String.valueOf(shortenedBytes);
没有按照你的想法去做。
为了获得数组中字节值的字符串表示,您需要实现一些实用方法。
此外,如果对 MessageDigest.getInstance("MD5");
的调用曾经抛出一个 NoSuchAlgorithmException
,您的程序稍后会在此处崩溃 md.update (key.getBytes());
与 NullPointerException
。
关于java - MD5 对相同的输入返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25542511/