MD5 Message Digest Java

David Jackson picture David Jackson · Mar 10, 2013 · Viewed 7.2k times · Source

I'm trying to convert two strings from an String List into MD5 message digests.

My String List is called "usernamepassword".

try {
            MessageDigest mdg = MessageDigest.getInstance("MD5");      

            mdg.update(usernamepassword.get(0).getBytes(), 0, usernamepassword.get(0).length());
            mdg.update(usernamepassword.get(1).getBytes(), 1, usernamepassword.get(0).length());     


        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(UPCheck.class.getName()).log(Level.SEVERE, null, ex);
        }

My question is -

A: Is that the correct way of doing it? B: How would I return it so I could use each individual MD5 hash in another class?

Answer

Jon Skeet picture Jon Skeet · Mar 10, 2013

A: Is that the correct way of doing it?

No, for four reasons:

1) You're using the default character encoding, instead of specifying a particular encoding. I'd recommend using UTF-8.

2) You're currently using the length of the string in characters to specify how many bytes to use

3) If you want separate digests (one per string) you should use separate MessageDigest instance for each one, or call reset between calls

4) You're not actually doing anything with the digests at the moment.

I suggest you extract the "MD5 of a string in a particular encoding" into a separate method:

public static byte[] getMd5OfUtf8(String text) {
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");      
        return digest.digest(text.getBytes("UTF-8"));
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException("No MD5 implementation? Really?");
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException("No UTF-8 encoding? Really?");
    }
}

Then you can call it for each of the list elements you're interested in - it's not clear what you're trying to do with the digests afterwards, but you probably want them separately...

EDIT: As noted in comments, MD5 really isn't a great hash choice these days. Something like SHA-256 with a salt would be better, but for real secure applications you should probably read some modern literature on the topic. (I'm not an expert so don't want to sound too authoritative.)