MD5 and SHA hashing in Java
Monday, July 9th, 2007
MD5 and SHA are two popular hashing algorithms with a variety of uses. An implementation of these algorithms is included in J2SE, under the java.security package.
Pretty often you may need to store some information in encrypted form, like a password stored in a database. You can use the MD5 algorithm to encrypt the original String and then safely store it in the database. Later, you authenticate by comparing the digests. This sample code returns the MD5 digest of a String:
You may also need to calculate the MD5 digest of the contents of a whole file (exactly as the md5 unix command does). This is useful in file integrity checks. In this case you have to read chunks from the file and repeatedly call the update() method. This way you avoid loading the whole of large files into memory. Here is some sample code:
The above methods return the digest as a 16-byte-long array of bytes. You can get the corresponding hexadecimal representation using this method:
To switch to the SHA hashing algorithm you simply have to pass "SHA" in the getInstance() method.
Pretty often you may need to store some information in encrypted form, like a password stored in a database. You can use the MD5 algorithm to encrypt the original String and then safely store it in the database. Later, you authenticate by comparing the digests. This sample code returns the MD5 digest of a String:
public static byte[] md5( String st )
throws NoSuchAlgorithmException
{
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(st.getBytes());
return md5.digest();
}You may also need to calculate the MD5 digest of the contents of a whole file (exactly as the md5 unix command does). This is useful in file integrity checks. In this case you have to read chunks from the file and repeatedly call the update() method. This way you avoid loading the whole of large files into memory. Here is some sample code:
public static byte[] md5( File file )
throws NoSuchAlgorithmException, IOException
{
MessageDigest md5 = MessageDigest.getInstance("MD5");
InputStream in = new FileInputStream(file);
byte[] buffer = new byte[1024];
int count;
while ((count = in.read(buffer)) > 0)
md5.update(buffer,0,count);
return md5.digest();
}The above methods return the digest as a 16-byte-long array of bytes. You can get the corresponding hexadecimal representation using this method:
public static String byteArrayToHex( byte[] bytes )
{
StringBuilder builder =
new StringBuilder(bytes.length*2);
for (byte b : bytes)
builder.append(Integer.toHexString((b & 0xFF) +
0x100).substring(1));
return builder.toString();
}To switch to the SHA hashing algorithm you simply have to pass "SHA" in the getInstance() method.

