Generate File Hash

Generate a File Hash from a source file.

Javadoc available at https://www.javatapas.com/docs/javatapas/io/GenerateFileHash.html


public static String generateFileHash(File inFile, String algorithm) throws IOException, NoSuchAlgorithmException {

	MessageDigest messageDigest = MessageDigest.getInstance(algorithm);

	InputStream is = new FileInputStream(inFile);

	byte[] buffer = new byte[1024];
	int numRead = is.read(buffer);

	while (numRead >= 0) {
		if (numRead > 0) {messageDigest.update(buffer, 0, numRead);}
		numRead = is.read(buffer);
	}

	is.close();

	byte[] bytes = messageDigest.digest();

	StringBuffer hash = new StringBuffer();
	for (byte b : bytes) {hash.append(String.format("%02x", b));} // convert to hex

	return hash.toString();
}