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

About the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
Ayoub
Guest
Ayoub

Hi all,
I found that the hash for the input “hello world!” gives different results .

Hex format : 323b1637c7999942fbebfe5d42fe15dbfe93737577663afa0181938d7ad4a2ac
Hex format : 323b1637c7999942fbebfe5d42fe15dbfe93737577663afa181938d7ad4a2ac

like what @StYleZ said there is a 0(“zero”) missing.

Steve Newson
Guest
Steve Newson

Alternative method for generating the hex string:

javax.xml.bind.DatatypeConverter.printHexBinary(byteData).toLowerCase()

Suraj
Guest
Suraj

How to decrypt SHA-2 256 algorithm??

pancho
Guest
pancho

te amo

Savani
Guest
Savani

Hi Mkyong,

How we can compare two hashed values for the same salt ? Please share sample code / links etc.

Regards, Savani

Pallav Raj
Guest
Pallav Raj

Hi MkYong… I have a question. if anyone can answer please reply to this comment. My question is, I encrypted a password with SHA-256. Now I am logging to my application with my userId and password. Now I have String password and encrypted password. How can I validate my user? Do i need to decrypt my password, if yes, then if possible please provide solution. Thank you in Advance.

sandeep
Guest
sandeep

can you get the original string from hash code .If not then what is use if Hashing ?

Zoran Davidovi?
Guest
Zoran Davidovi?

“The possible MessageDigest algorithm are SHA-1, SHA-256, SHA-384, and SHA-512, you can check the reference for the detail.” You forgot SHA-224 algorithm.

Guillaume Husta
Guest
Guillaume Husta

We can also get the complete list with :
Set algosMessageDigest = Security.getAlgorithms(“MessageDigest”);
;-)

Yuriy Tereschuk
Guest
Yuriy Tereschuk

@Mkyong, can you update the second reference in References part, because it’s not valid.

diya
Guest
diya

how do i generate hash value by passing multiple parameters? If i need to send 2 strings and generate a hash value ..is it possible?

UN-deathx
Guest
UN-deathx

Thank’s

Zeza
Guest
Zeza
hi all, i’m very new in programming, i have urgent task: i have to send message signed by some key i have an example on Cscharp but i need it written on Java, please help me! ************************************************************************************************************ using System; using System.Collections.Generic; using System.Windows.Forms; using System.Text; using System.Net; using System.Net.Security; using System.Globalization; using System.Security.Policy; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace uwcfs.sample { static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main() { string msg = “”; ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidationCB); msg += Environment.NewLine + ” — MoneyTransfer — ” + Environment.NewLine + Environment.NewLine;… Read more »
trackback
Securely Storing passwords in a Database using a Hash Algorithm in Java | Technotes

[…] If you are interested in further information about password security levels see this fine article. Another way of using the MessageDigest. Java SHA Hashing Example […]

mery
Guest
mery

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

sheeysong
Guest
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
Guest
Bambat
String digestAlgorithm = "SHA-256"; String fileName = "/tmp/test"; 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 < 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("%02x", d)); } result = sb.toString();
trackback
Securely Storing passwords in a Database using a Hash Algorithm in Java « wt232

[…] If you are interested in further information about password security levels see this fine article. Another way of using the MessageDigest. Java SHA Hashing Example […]

Sudhakar
Guest
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 < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 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
Guest
Daniel Serodio

You forgot to close the FileInputStream in the first example.

BillR
Guest
BillR

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

venkateswarlu
Guest
venkateswarlu

what is package com.mkyong.test;

Sudhakar
Guest
Sudhakar

com.mkyong.test;

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

Santis
Guest
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
Guest
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
Guest
Santis

That’s the point. Thank you.

StYleZ
Guest
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

ChaZ
Guest
ChaZ

What was your input?

FixingError
Guest
FixingError

The reason that the 2nd method would output wrong because it eats up leading zero of any hex-pair value. For example, a hex value of x07 will be output as 7 in the string. As a result, the 2nd method will output a wrong result for a hex value from x00 to x0F. Hope this help people in the future.

Joe
Guest
Joe

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

Bart Oudhoff
Guest
Bart Oudhoff

Thanks, this helped me out a lot!

Neha
Guest
Neha

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

Lucky Luck
Guest
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

trackback
Hashing and Checksum in Java « Awe struck

[…] came across this article which gives a simple means to perform File Checksum and Hashing String in […]

John
Guest
John

why don’t you use DigestInputStream?

trackback
Spring Security password hashing example

[…] To hash string with SHA or MD5 algorithm, refer to this Java SHA example or using Jacksum, third-party Java library. For readability, we will use Jacksum to perform […]

Jersey Jim
Guest
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
Guest
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!