Monday, 20 February 2017

HOW TO GENERATE SHA1 HASH VALUE OF 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



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



Friday, 17 February 2017

Spring: PropertyPlaceholderConfigurer: Load multiple property files

In my previous post, I explained how to load a property file using PropertyPlaceholderConfigurer. In real world scenario, an application requires to maintain multiple property files. By using PropertyPlaceholderConfigurer class, you can load multiple property files.

Following statement loads the property files mail.properties, db.properties.
 <bean id="dbProperties"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

  <property name="locations">
   <list>
    <value>classpath:mail.properties</value>
    <value>classpath:db.properties</value>
   </list>
  </property>

 </bean>

Following is the complete working application.


mail.properties
app.contactUs=krishna@krishna.com
app.reportTo=help@krishna.com

db.properties
db.hostName=abc.xyz.com
db.port=8081
db.userName=krish@gmail.com
db.password=secret

Database.java
package com.sample.pojo;

public class Database {
 private String hostName;
 private String port;
 private String userName;
 private String password;

 public String getHostName() {
  return hostName;
 }

 public void setHostName(String hostName) {
  this.hostName = hostName;
 }

 public String getPort() {
  return port;
 }

 public void setPort(String port) {
  this.port = port;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Database [hostName=").append(hostName).append(", port=").append(port).append(", userName=")
    .append(userName).append(", password=").append(password).append("]");
  return builder.toString();
 }

}

Application.java
package com.sample.pojo;

public class Application {
 private String contactUs;
 private String mailTo;

 public String getContactUs() {
  return contactUs;
 }

 public void setContactUs(String contactUs) {
  this.contactUs = contactUs;
 }

 public String getMailTo() {
  return mailTo;
 }

 public void setMailTo(String mailTo) {
  this.mailTo = mailTo;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Application [contactUs=").append(contactUs).append(", mailTo=").append(mailTo).append("]");
  return builder.toString();
 }

}

myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="dbProperties"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

  <property name="locations">
   <list>
    <value>classpath:mail.properties</value>
    <value>classpath:db.properties</value>
   </list>
  </property>

 </bean>

 <bean id="database" name="database" class=" com.sample.pojo.Database">
  <property name="hostName" value="${db.hostName}" />
  <property name="port" value="${db.port}" />
  <property name="userName" value="${db.userName}" />
  <property name="password" value="${db.password}" />
 </bean>
 
 <bean id="application" name="application" class=" com.sample.pojo.Application">
  <property name="contactUs" value="${app.contactUs}" />
  <property name="mailTo" value="${app.reportTo}" />
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sample.pojo.Application;
import com.sample.pojo.Database;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Database database = context.getBean("database", Database.class);
  Application application = context.getBean("application", Application.class);

  System.out.println(database);
  System.out.println(application);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run HelloWorld.java, you can able to see following output.

Database [hostName=abc.xyz.com, port=8081, userName=krish@gmail.com, password=secret]
Application [contactUs=krishna@krishna.com, mailTo=help@krishna.com]







Previous                                                 Next                                                 Home