Monday, December 22, 2008

Bookmark and Share

A geo cache which a friend of mine tried to spot recently (see here, in German) required to do some MD5 hash calculation.

Using Java's java.security.MessageDigest this is actually a no-brainer, and if you need MD5 hashes for short strings rather than whole files, a utility class such as the following comes in handy:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MD5Helper {

    public static String getMD5Hash(String input) {

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());

            return new BigInteger(1, messageDigest).toString(16);
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

}

If you want to have an MD5 hash for a whole file, you probably don't want to read this file entirely into a string. In that case you can use MessageDigest's methods update(byte[] input) and digest() to calculate the hash chunk-wise, as you are reading the file into a buffer. A complete code example can be found here.

If you do not necessarily have to work with MD5 hashes, Apache Commons IO might be an alternative as well. Its class FileUtils offers – besides a lot of other very convenient functions, in especially for copying files and directories – the method checksumCRC32(File file), which calculates a file checksum using the CRC32 routine.

No comments: