Today, we have another little code snipped. Sometimes, we need to transfer files between systems, and in these cases, it is usually interesting to have some kind of system to check the file content integrity. In these cases, it is when a checksum can be very useful. Here we have a little implementation done in Java. Simple to write, simple to use.
package com.wordpress.binarycoders.checksum;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
public class CheckSum {
private static final String MD5 = "MD5";
private static final String SHA1 = "SHA-1";
public static String md5CheckSum(byte[] content) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(MD5);
return byteArray2Hex(md.digest(content));
}
public static String sha1CheckSum(byte[] content) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(SHA1);
return byteArray2Hex(md.digest(content));
}
private static String byteArray2Hex(final byte[] hash) {
String result = "";
try (Formatter formatter = new Formatter()) {
for (byte b : hash) {
formatter.format("%02x", b);
}
result = formatter.toString();
}
return result;
}
}
See you.