EyeQ Tech
EyeQ Tech

Reputation: 7378

MD5 returns different values for the same input

I'm on Android, so it's just java, I have the same input strings, but getting different values each time. I am missing anything? Thanks

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;
    }

Input string:

{"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":"[email protected]_1409180400","class":"event","endTime":1409209200,"location":{"lng":151.20785,"lat":-33.85926},"priority":0},{"startTime":1409148000,"id":"[email protected]_1409148000","class":"event","endTime":1409234340,"location":{"lng":151.18089,"lat":-33.89153},"priority":0}]}

Update: so many valid answers, thanks. I pick the one that is easiest to change. Cheers.

Upvotes: 1

Views: 1477

Answers (3)

Devrim
Devrim

Reputation: 15533

As @Henry explained the issue at his answer, String.valueOf(shortenedBytes) must be changed.

Replace this;

shortenedKey = String.valueOf(shortenedBytes);

to this;

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

You can use Base64 from Bouncycastle

Download the jar

Upvotes: 1

Lifecube
Lifecube

Reputation: 1188

check the modified version. you could use base64 encoding for bytes

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;
}

Upvotes: 0

Henry
Henry

Reputation: 43788

This line

shortenedKey = String.valueOf(shortenedBytes);

is not doing what you think.

In order to get a string representation of the byte values inside the array you need to implement a little utility method.

Furthermore, if the call to MessageDigest.getInstance("MD5"); ever throws a NoSuchAlgorithmException your program will crash a little later here md.update(key.getBytes()); with a NullPointerException.

Upvotes: 1

Related Questions