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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import javax.xml.bind.DatatypeConverter; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; class Main { public static void main(String[] args) throws Exception { String password = "SHA-256"; MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] digest = md.digest(password.getBytes(StandardCharsets.UTF_8)); String sha256 = DatatypeConverter.printHexBinary(digest).toLowerCase(); // print SHA-256 Message Digest System.out.println(sha256); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import com.google.common.base.Charsets; import com.google.common.hash.HashCode; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; class Main { public static void main(String[] args) throws Exception { String password = "SHA-256"; Hasher hasher = Hashing.sha256().newHasher(); hasher.putString(password, Charsets.UTF_8); HashCode sha256 = hasher.hash(); System.out.println(sha256); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import org.apache.commons.codec.digest.DigestUtils; class Main { public static void main(String[] args) throws Exception { String password = "SHA-256"; String sha256 = DigestUtils.sha256Hex(password); System.out.println(sha256); } } |
Output:
bbd07c4fc02c99b97124febf42c7b63b5011c0df28d409fbb486b5a9d2e615ea
That’s all about generating the SHA-256 hashcode in Java.