Java SHA Hashing Example

The SHA hash functions are a set of cryptographic hash functions designed by the National Security Agency (NSA) and published by the NIST as a U.S. Federal Information Processing Standard. SHA stands for Secure Hash Algorithm. The three SHA algorithms are structured differently and are distinguished as SHA-0, SHA-1, and SHA-2. The SHA-2 family uses an identical algorithm with a variable digest size which is distinguished as SHA-224, SHA-256, SHA-384, and SHA-512.

SHA-2 is believe the most secure hashing algorithm as this article is written, here are few examples for the SHA implementation. The possible MessageDigest algorithm are SHA-1, SHA-256, SHA-384, and SHA-512, you can check the reference for the detail.

1. File checksum with SHA-256

It will use SHA-256 hashing algorithm to generate a checksum for file “c:\\loging.log”.

package com.mkyong.test;
 
import java.io.FileInputStream;
import java.security.MessageDigest;
 
public class SHACheckSumExample 
{
    public static void main(String[] args)throws Exception
    {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        FileInputStream fis = new FileInputStream("c:\\loging.log");
 
        byte[] dataBytes = new byte[1024];
 
        int nread = 0; 
        while ((nread = fis.read(dataBytes)) != -1) {
          md.update(dataBytes, 0, nread);
        };
        byte[] mdbytes = md.digest();
 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mdbytes.length; i++) {
          sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
        }
 
        System.out.println("Hex format : " + sb.toString());
 
       //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
    	for (int i=0;i<mdbytes.length;i++) {
    	  hexString.append(Integer.toHexString(0xFF & mdbytes[i]));
    	}
 
    	System.out.println("Hex format : " + hexString.toString());
    }
}
Output
Hex format : 21a57f2fe765e1ae4a8bf15d73fc1bf2a533f547f2343d12a499d9c0592044d4
Hex format : 21a57f2fe765e1ae4a8bf15d73fc1bf2a533f547f2343d12a499d9c0592044d4

2. Hashing String with SHA-256

It will use SHA-256 hashing algorithm to generate a hash value for a password “123456”.

package com.mkyong.test;
 
import java.security.MessageDigest;
 
public class SHAHashingExample 
{
    public static void main(String[] args)throws Exception
    {
    	String password = "123456";
 
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(password.getBytes());
 
        byte byteData[] = md.digest();
 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
 
        System.out.println("Hex format : " + sb.toString());
 
        //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
    	for (int i=0;i<byteData.length;i++) {
    		String hex=Integer.toHexString(0xff & byteData[i]);
   	     	if(hex.length()==1) hexString.append('0');
   	     	hexString.append(hex);
    	}
    	System.out.println("Hex format : " + hexString.toString());
    }
}
Output
Hex format : 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
Hex format : 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92

Reference

  1. http://en.wikipedia.org/wiki/SHA_hash_functions
  2. http://java.sun.com/j2se/1.4.2/docs/guide/security/CryptoSpec.html#AppA
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Iwan

    I think the best way to create the hex format is using the runtime libs.
    Use this:

    BigInteger bigInt = new BigInteger(1, mdbytes);
    output = bigInt.toString(16);

    Got that tip from http://stackoverflow.com/questions/3103652/hash-string-via-sha-256-in-java

  • Pingback: Securely Storing passwords in a Database using a Hash Algorithm in Java | Technotes()

  • mery

    Method 2 gives another result..
    A problem by “01”
    Hex format : 8a47c4856ca6de2a016f3a2ab10ef79362ecfc73b038bccfa6eff48afcef4244
    Hex format : 8a47c4856ca6de2a16f3a2ab1ef79362ecfc73b038bccfa6eff48afcef4244

  • sheeysong

    Hi Yong,
    Thanks for this simple toHexString() code block, can you shed your light to reverse it back to the original ascii String in Java? I tried to write a block of code to convert your MessageDigest byte[] back to String (String HexByteToString(byte[] digestByte), but not quite right somehow.
    Thanks,

    ~Jing

  • Bambat
    String digestAlgorithm = &quot;SHA-256&quot;;
    String fileName = &quot;/tmp/test&quot;;
    String result;
    // Obtain a message digest object.
                MessageDigest md = MessageDigest.getInstance(digestAlgorithm);
     
                // Calculate the digest for the given file.
                DigestInputStream in = new DigestInputStream(
                        new FileInputStream(fileName), md);
                byte[] buffer = new byte[8192];
                while (0 &lt; in.read(buffer)){}
                // gets digest
                byte[] digest = md.digest();
                // convert the byte to hex format
                StringBuilder sb = new StringBuilder();
                for (byte d : digest) {
                    sb.append(String.format(&quot;%02x&quot;, d));
                }
                result = sb.toString();
  • Pingback: Securely Storing passwords in a Database using a Hash Algorithm in Java « wt232()

  • Sudhakar

    I tried, { 2. Hashing String with SHA-256 } Example.

    //convert the byte to hex format method 1
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i &lt; byteData.length; i++) {
    sb.append(Integer.toString((byteData[i] &amp; 0xff) + 0x100, 16).substring(1));
    }

    When i refresh the page. this code gets looped.
    Example:
    First Output: 1x2x3x
    Second Output: 1x2x3x1x2x3x
    Third Output: 1x2x3x1x2x3x1x2x3x

    But second one works good.

  • Daniel Serodio

    You forgot to close the FileInputStream in the first example.

  • BillR

    getBytes() is platform dependent. you should specify an encoding so that it works no matter what encoding is used on your platform.

  • venkateswarlu

    what is package com.mkyong.test;

    • Sudhakar

      com.mkyong.test;

      Its your current package or folder.
      You are writing your code in com/mkyong/test folder.

  • Santis

    Hi,
    Thank you for your article. Second method of converting the byte to hex is more efficient than first one (about 30%).
    But I have different problem. When I compared Java SHA-256 hashing with Linux program (echo 123456 | sha256sum) I’ve got different results (for “123456”):
    JAVA: 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
    LINUX: e150a1ec81e8e93e1eae2c3a77e66ec6dbd6a3b460f89c1d08aecf422ee401a0

    I can’t find reason, do you know one?

    • einsty

      Note that you will need to use echo -n 123456 | sha256sum

      The echo command includes a carriage return i believe and that is getting hashed as well… that’s the reason your result will be different.

      • Santis

        That’s the point. Thank you.

  • StYleZ

    Hi @ll,

    1. File checksum with SHA-256 -> //convert the byte to hex format method 2 = doesn’t work correntcly!

    Here my output:
    Hex format : da84e5104ec02982515127adda821ffc533acf7f07bd9b5839f31239e888feea
    Hex format : da84e5104ec02982515127adda821ffc533acf7f7bd9b5839f31239e888feea

    As you may have noticed there is as 0(“zero”) missing.
    Methond 1 is fine.

    Thx for this Tutorail – it helped me alot!

    Greets
    StYleZ

  • Joe

    Thank you so much, this tutorial is very useful and clear.

  • Bart Oudhoff

    Thanks, this helped me out a lot!

    • Neha

      But , this is not helped me a lot!!!!!!!!!!!!!!!!!!!!!!!!

  • Lucky Luck

    Hi,
    Can you please tell me that how can we convert the SHA-256 Hash into simple text, using javascript, c#.net?
    Thanks

  • Pingback: Hashing and Checksum in Java « Awe struck()

  • John

    why don’t you use DigestInputStream?

  • Pingback: Spring Security password hashing example()

  • Jersey Jim

    Another byte to hex format method:

    java.math.BigInteger number = new java.math.BigInteger(1, byteData);
    System.out.println(String.format("%1$032x", number));

    I saw this idea in the comments at: http://www.spiration.co.uk/post/1199/Java-md5-example-with-MessageDigest

    • Jersey Jim

      -oops should have been:

      java.math.BigInteger number = new java.math.BigInteger(1, byteData);
      System.out.println(String.format("%1$064x", number));

      Sorry about that!

  • forber

    Wrong:(2. Hashing String with SHA-256)
    System.out.println(Hex format : ” + hexString.toString());

    Right
    System.out.println(“Hex format : ” + hexString.toString());

    • http://www.mkyong.com mkyong

      Article is updated, thanks for point out the typo mistake.

      • Rishabh

        Hi Sir,

        Its really a very good job you are doing
        Just a suggestion, there is no searching option available on this site.
        Could you please add the same.

      • Dipika

        Hi Sir,

        Its really a very good job you are doing
        Just a suggestion, there is no searching option available on this site.
        Could you please add the same.