gammaraptor
gammaraptor

Reputation: 1886

md5 hashes in Java from MessageDigest don't matchup

I have an object called users that I use to store user objects that have credential information.

I call this code to make a new default user.

user def = new user("admin","admin",md5hash(("osa").toCharArray()),1,-1);

This def user is added to the array.

These users are stored inside an array. When I loop through the array to check whether it is valid or not, I use this snippet of code to output information about users inside the array, namely the username and password in string format from a byte array.

System.out.println(userarray.get(x).username);
System.out.println((userarray.get(x).password).toString());

The passwords are all encrypted in md5 and stored as a byte array using this code:

byte[] md5hash(char[] passwd) {
    String passwdtext = new String(passwd);
byte[] passdigest = null;
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.reset();
        md5.update(passwdtext.getBytes("UTF-8"));
        passdigest = md5.digest();

    } catch (NoSuchAlgorithmException e) {

        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return passdigest;
}

When I try entering "admin" for user and "osa" for the password, I output these as well and compare them with the values in the array

I get the following:

admin [B@2b12e7f7

and compare to the value inside the array: admin [B@663b1f38

Why are they different?

Upvotes: 1

Views: 1664

Answers (2)

Edward Samson
Edward Samson

Reputation: 2425

You are calling toString() on a byte[] which is just calling Object.toString(). What you get does not represent the contents of the array but its hashCode, instead.

If you are looking to get an MD5 string I would suggest using DigestUtils.md5Hex() from the Apache Commons Codec project. This replaces your whole md5hash() method.

If you are not keen on adding an external dependency and just want to implement this for yourself then you just have to decode a String representation for each byte value in your byte array, such as by Arrays.toString().

Upvotes: 1

Brandon DuRette
Brandon DuRette

Reputation: 4870

The toString() byte array does not encode the data. What you are looking at is the memory address of said arrays. The "[B" means byte array. The hex after that is the address.

Instead, you should invoke Arrays.toString(digestArray); which will print the actual values in the array.

Also, it's not clear by the code that you posted, but if you're trying to use == to compare the two arrays, that will fail for the same reason. The == operator on arrays compares memory addresses. Here again, you should use Arrays.equals(a1, a2) to compare.

Upvotes: 2

Related Questions