Generate SHA-256 hashcode in Java

Google Translate Icon

The SHA-256 algorithm is a widely used hash method producing a 256-bit hash value. This post will discuss different methods to generate the SHA-256 hashcode in Java using MessageDigest class, Guava, and Apache Commons library.

1. Using MessageDigest class

The idea is to get an instance of SHA-256 message digest using the java.security.MessageDigest class getInstance() method, which takes digest algorithm. Then we call the digest(input) method that first calls update(input), passing the input array to the update method, then calls digest(). We can make an explicit call to the update() method several times for large inputs.

Note that the java.xml.bind is no longer contained on the default classpath starting Java SE 9. In Java 11, they are completely removed from the JDK.

Download Code

Output:

bbd07c4fc02c99b97124febf42c7b63b5011c0df28d409fbb486b5a9d2e615ea

2. Using Guava Library

We can also use third-party libraries like Google’s Guava library for generating the SHA-256 hashcode. This is demonstrated below:

Download Code

Output:

bbd07c4fc02c99b97124febf42c7b63b5011c0df28d409fbb486b5a9d2e615ea

3. Using Apache Commons Lang

Alternatively, Apache Commons library can also be used which provides org.apache.commons.codec.digest.DigestUtils class to replace MessageDigest Class.

Download Code

Output:

bbd07c4fc02c99b97124febf42c7b63b5011c0df28d409fbb486b5a9d2e615ea

That’s all about generating the SHA-256 hashcode in Java.

Rate this post

Average rating 4.43/5. Vote count: 7

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?




Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding :)



Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Do NOT follow this link or you will be banned from the site!