We’ve previously shown how to create an MD5 sum for a file. If you don’t have a file and instead just need an MD5 sum for a byte array then you can achieve it using the following code.
// Data is the byte array we need an MD5 sum for
byte[] data = getDataFromWhereever();
// Get an MD5 implementation of MessageDigest
MessageDigest md = MessageDigest.getInstance("MD5");
// Convert the MD5 byte array to a hex string
String md5 = new BigInteger(1, md.digest(data)).toString(16);
written by objects
\\ tags: BigInteger, md5, MessageDigest, string
You can use BigInteger class to convert a byte array into its hex (or binary) representation. However for large byte arrays this method is slow.
For large byte arrays and where performance is important you can use the following utility method to convert each byte to its binary representation.
public static String toBinaryString(byte n) {
StringBuilder sb = new StringBuilder("00000000");
for (int bit = 0; bit < 8; bit++) {
if (((n >> bit) & 1) > 0) {
sb.setCharAt(7 - bit, '1');
}
}
return sb.toString();
}
written by objects
\\ tags: BigInteger, binary, byte, conversion, StringBuilder
We can use an MD5 implementation of the MessageDigest class to calculate the MD5 sum of a file (or any array of bytes). Once we have that it is simply a matter of feeding the contents of the file to the digest and have it calculate the MD5 sum as shown in the following example.
// Get an MD5 implementation of MessageDigest
MessageDigest digest = MessageDigest.getInstance("MD5");
// Open file and read contents
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[8192];
int read = 0;
while( (read = is.read(buffer)) >= 0)
{
// pass data read from file to digest for processing
digest.update(buffer, 0, read);
}
is.close();
// Get the MD5 sum
byte[] md5sum = digest.digest();
// (Optionally) convert the MD5 byte array to a hex string
String md5sumHex = new BigInteger(1, md5sum).toString(16);
written by objects
\\ tags: BigInteger, hex, md5, md5sum, MessageDigest