The SHA-256 algorithm is a widely used hash function 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.