MD5为同一输入返回不同的值

时间:2014-08-28 06:53:43

标签: java android md5

我在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}]}

更新:这么多有效答案,谢谢。我选择最容易改变的那个。欢呼声。

3 个答案:

答案 0 :(得分:1)

这一行

shortenedKey = String.valueOf(shortenedBytes);

没有按照你的想法行事。

为了获得数组中字节值的字符串表示,您需要实现一个小实用程序方法。

此外,如果对MessageDigest.getInstance("MD5");的调用引发NoSuchAlgorithmException,您的计划会在稍后md.update(key.getBytes()); NullPointerException时崩溃。

答案 1 :(得分:1)

@Henry在回答时解释了这个问题,String.valueOf(shortenedBytes)必须改变。

替换它;

shortenedKey = String.valueOf(shortenedBytes);

到此;

shortenedKey = new String(Base64.encode(shortenedBytes))

您可以使用Bouncycastle

中的Base64

Download the jar

答案 2 :(得分:0)

检查修改后的版本。 你可以使用base64编码的字节

private String getShortenedKey(String key) {
    String shortenedKey=null;
    MessageDigest md = null;
    LogUtils.LOGD(HASH_ALGO, "before key: "+ System.currentTimeMillis());
    try {
        md = MessageDigest.getInstance("MD5");

        md.update(key.getBytes());
        byte[] shortenedBytes = md.digest();
        shortenedKey = Base64.encodeToString(shortenedBytes, Base64.NO_WRAP);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        shortenedKey = key;
    }
    LogUtils.LOGD(HASH_ALGO, "after key: "+ System.currentTimeMillis());

    return shortenedKey;
}