#385
[Java] Generate hash code from a file
/** * Generate a hash for a file. */ public final class HashUtils { /** Default hash algorithm. */ public static final Algo DEFAULT_ALGO = Algo.MD5; /** * Define all hash algorithm. */ public enum Algo { /** MD5. */ MD5("MD5"), /** SHA1. */ SHA1("SHA-1"), /** SHA256. */ SHA256("SHA-256"), /** SHA384. */ SHA384("SHA-384"), /** SHA512. */ SHA512("SHA-512"); private String value; /** * Default constructor. * * @param name * of the algo */ Algo(final String name) { value = name; } /** * @return the value */ String getValue() { return value; } /** * Set the value. * * @param name * of the value to set */ void setValue(final String name) { value = name; } }; /** * Default private constructor. */ private HashUtils() { } /** * Return hash representation of the file content. (using default algorithm) * * @param filename * name of the file to hash * @return hash representation of the file * @throws Exception * in case of error */ public static String getChecksum(final String filename) throws Exception { return getChecksum(filename, DEFAULT_ALGO); } /** * Return hash representation of the file content. (using specific algorithm) * * @param filename * name of the file to hash * @param algo * used to hash the file * @return hash representation of the file * @throws Exception * in case of error */ public static String getChecksum(final String filename, final Algo algo) throws Exception { byte[] b = createChecksum(filename, algo); String result = ""; for (int i = 0; i < b.length; i++) { result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1); } return result; } /** * Read and parse file to hash. * * @param filename * name of the file to hash * @param algo * used to hash the file * @return byte array representing hash * @throws Exception * in case of error */ private static byte[] createChecksum(final String filename, final Algo algo) throws Exception { InputStream fis = new FileInputStream(filename); byte[] buffer = new byte[1024]; MessageDigest complete = MessageDigest.getInstance(algo.getValue()); int numRead; do { numRead = fis.read(buffer); if (numRead > 0) { complete.update(buffer, 0, numRead); } } while (numRead != -1); fis.close(); return complete.digest(); } }
Comments are currently closed.