繁体   English   中英

MD5对于相同的输入返回不同的值

[英]MD5 returns different values for the same input

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

正如@Henry在他的回答中解释的问题一样,必须更改String.valueOf(shortenedBytes) shortenedBytes String.valueOf(shortenedBytes)

更换它;

shortenedKey = String.valueOf(shortenedBytes);

对此

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

您可以从Bouncycastle使用Base64

下载罐子

检查修改后的版本。 您可以对字节使用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;
}

暂无
暂无

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

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