Monday, 20 February 2017

Generate content hash of a file

Message digests are secure one-way hash functions that take arbitrary-sized data and output a fixed-length hash value. In my previous post, I explained about message digest and how to compute message digest. I recommend you to go through my previous post before reading this.

In this post, I am going to explain how to compute hash value of a file. At the time of writing this article, java supports following message digest algorithms.

a.   SHA-1
b.   SHA-224
c.   SHA-256
d.   SHA-384
e.   SHA-512
f.    MD5
g.   MD2

I implemented FileContentHashUtil class that provides following public static methods that compute and return the hash value of a file.

Method
Description
public static Optional<String> getMD2DigestOfFile(final String fileName)
Compute hash value of file using MD2 algorithm.
public static Optional<String> getMD5DigestOfFile(final String fileName)
Compute hash value of file using MD5 algorithm.
public static Optional<String> getSHA1DigestOfFile(final String fileName)
Compute hash value of file using SHA-1 algorithm.
public static Optional<String> getSHA224DigestOfFile(final String fileName)
Compute hash value of file using SHA-224 algorithm.
public static Optional<String> getSHA256DigestOfFile(final String fileName)
Compute hash value of file using SHA-256 algorithm.
public static Optional<String> getSHA384DigestOfFile(final String fileName)
Compute hash value of file using SHA-384 algorithm.
public static Optional<String> getSHA512DigestOfFile(final String fileName)
Compute hash value of file using SHA-512 algorithm.

package com.sample.util;

import java.io.FileInputStream;
import java.security.MessageDigest;
import java.util.Optional;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Utility class to compute content hash of a file.
 * 
 * @author Hari Krishna
 *
 */
public class FileContentHashUtil {
 private static final Logger log = LogManager.getLogger();

 private static Optional<String> getContentHash(final String filePath, final String algorithm) {
  if (filePath == null || filePath.isEmpty()) {
   log.error("file name can't be null");
   return Optional.empty();
  }

  if (algorithm == null || algorithm.isEmpty()) {
   log.error("Algorithm can't be null");
   return Optional.empty();
  }

  try (FileInputStream inputStream = new FileInputStream(filePath)) {

   MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
   byte[] buffer = new byte[32768];
   int numberOfReadBytes = -1;

   while ((numberOfReadBytes = inputStream.read(buffer)) != -1) {
    messageDigest.update(buffer, 0, numberOfReadBytes);
   }

   String contentHash = getContentStreamHashValue(messageDigest.digest());

   return Optional.of(contentHash);
  } catch (Exception e) {
   log.error("Error occured while computing hash of the file {}, Error : {}", filePath, e.getMessage());
   log.error(e);
  }

  return Optional.empty();
 }

 private static String getContentStreamHashValue(byte[] data) {
  StringBuilder stringBuilder = new StringBuilder();
  for (byte element : data) {
   if ((0xFF & element) < 0x10) {
    stringBuilder.append("0");
   }
   stringBuilder.append(Integer.toHexString(0xFF & element));
  }
  return stringBuilder.toString();
 }

 public static Optional<String> getMD2DigestOfFile(final String fileName) {
  return getContentHash(fileName, "MD2");
 }

 public static Optional<String> getMD5DigestOfFile(final String fileName) {
  return getContentHash(fileName, "MD5");
 }

 public static Optional<String> getSHA1DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-1");
 }

 public static Optional<String> getSHA224DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-224");
 }

 public static Optional<String> getSHA256DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-256");
 }

 public static Optional<String> getSHA384DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-384");
 }

 public static Optional<String> getSHA512DigestOfFile(final String fileName) {
  return getContentHash(fileName, "SHA-512");
 }
}

package com.sample.util;

public class FileContentHashUtilTest {
 public static void main(String args[]){
  String filePath = "C:\\Users\\Krishna\\Documents\\Study\\Miscellaneous\\queues.pdf";
  
  String md2Hash = FileContentHashUtil.getMD2DigestOfFile(filePath).get();
  String md5Hash = FileContentHashUtil.getMD5DigestOfFile(filePath).get();
  String sha1Hash = FileContentHashUtil.getSHA1DigestOfFile(filePath).get();
  String sha224Hash = FileContentHashUtil.getSHA224DigestOfFile(filePath).get();
  String sha256Hash = FileContentHashUtil.getSHA256DigestOfFile(filePath).get();
  String sha384Hash = FileContentHashUtil.getSHA384DigestOfFile(filePath).get();
  String sha512Hash = FileContentHashUtil.getSHA512DigestOfFile(filePath).get();
  
  System.out.println("md2Hash : " + md2Hash);
  System.out.println("md5Hash : " + md5Hash);
  System.out.println("sha1Hash : " + sha1Hash);
  System.out.println("sha224Hash : " + sha224Hash);
  System.out.println("sha256Hash : " + sha256Hash);
  System.out.println("sha384Hash : " + sha384Hash);
  System.out.println("sha512Hash : " + sha512Hash);
  
  
 }
}

Sample output
md2Hash : b87c4416756a34856e7d77bcd74fd185
md5Hash : 743b07e773e1f989aed9e1d65f76013f
sha1Hash : 57632308cb2e5dac194c9300167312980b4599f8
sha224Hash : 8c25dc6e7886275f6d684705c5b18e5d866c6cf9966d74be9fe83d4c
sha256Hash : f24685985fe3e806e3fda5ad030092f6ca64bf91899ec82db83a63faaae7b7cf
sha384Hash : 434aa61c0058dad297ed447720ac915f3d7e7caa2c6008d3cfd327ecfa37157e95bb973cfc19883b7cc432c5f5c57998
sha512Hash : 3fd2f3c36dede32dc19dd1ae1b04bdcd3238d0cfdfe41da4e7be7d306a9dc92a9804d165c1820a81abc6b10ba8b48d39d5fd62c8cf5b83bbf488fcb7b74b74f8



You may like

Reference



No comments:

Post a Comment