Java SHA Hashing Example

In Java, you can use the MessageDigest class to do SHA hashing. In this article, we will show you how to use a SHA-256 algorithm to hash a String and generate a checksum for a file.

1. MessageDigest

1.1 Hash a string.

PasswordSha256.java

package com.mkyong.hashing;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordSha256 {

    public static void main(String[] args) throws NoSuchAlgorithmException {

        String password = "123456";

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashInBytes = md.digest(password.getBytes(StandardCharsets.UTF_8));

		// bytes to hex
        StringBuilder sb = new StringBuilder();
        for (byte b : hashInBytes) {
            sb.append(String.format("%02x", b));
        }
        System.out.println(sb.toString());

    }

}

Output


8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92

1.2 File checksum.

d:\server.log

123456
FileCheckSum.java

package com.mkyong.hashing;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileCheckSum {

    public static void main(String[] args) throws NoSuchAlgorithmException, IOException {

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashInBytes = checksum("d:\\server.log", md);
        System.out.println(bytesToHex(hashInBytes));

    }

    private static byte[] checksum(String filepath, MessageDigest md) throws IOException {

        try (DigestInputStream dis = new DigestInputStream(new FileInputStream(filepath), md)) {
            while (dis.read() != -1) ; //empty loop to clear the data
            md = dis.getMessageDigest();
        }

        return md.digest();

    }

    private static String bytesToHex(byte[] hashInBytes) {

        StringBuilder sb = new StringBuilder();
        for (byte b : hashInBytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();

    }

}

Output


8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92

2. Apache Commons Codec

Alternatively, try this Apache Commons Codecs library for hashing.

pom.xml

	<dependency>
		<groupId>commons-codec</groupId>
		<artifactId>commons-codec</artifactId>
		<version>1.11</version>
    </dependency>

2.1 Hash a String.

PasswordSha256.java

package com.mkyong.hashing;

import org.apache.commons.codec.digest.DigestUtils;

public class PasswordSha256 {

    public static void main(String[] args) {

        String password = "123456";

        String result = DigestUtils.sha256Hex(password);
        System.out.println(result);

    }

}

Output


8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92

2.2 File checksum.

FileCheckSum.java

package com.mkyong.hashing;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.FileInputStream;
import java.io.IOException;

public class FileCheckSum {

    public static void main(String[] args) throws IOException {

        String result = DigestUtils.sha256Hex(new FileInputStream("d:\\server.log"));
        System.out.println(result);

    }

}

Output


8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92

References

  1. Apache Commons Codec
  2. Java – How to convert Bytes to Hex
  3. Wikipedia – SHA-2
  4. MessageDigest JavaDoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
33 Comment threads
18 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
40 Comment authors
LionelAnuAks1316SurajPallav Raj Recent comment authors
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.

Suraj
Guest
Suraj

How to decrypt SHA-2 256 algorithm??

Savani
Guest
Savani

Hi Mkyong,

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

Regards, Savani

Steve Newson
Guest
Steve Newson

Alternative method for generating the hex string:

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

pancho
Guest
pancho

te amo

forber
Guest
forber

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

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

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

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 […]

John
Guest
John

why don’t you use DigestInputStream?

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 […]

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

Bart Oudhoff
Guest
Bart Oudhoff

Thanks, this helped me out a lot!

Joe
Guest
Joe

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

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

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?

venkateswarlu
Guest
venkateswarlu

what is package com.mkyong.test;

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.

Daniel Serodio
Guest
Daniel Serodio

You forgot to close the FileInputStream in the first 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.

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 […]

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();

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

mery
Guest
mery

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

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 […]

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 »

UN-deathx
Guest
UN-deathx

Thank’s

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?

Yuriy Tereschuk
Guest
Yuriy Tereschuk

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

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.

sandeep
Guest
sandeep

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