How to Generate SHA-256 Hash in Java With Example


Generate SHA-256 Hash in Java

The SHA-256 stands for "Secure Hash Algorithm 256-bit" is a cryptographic "hash function" that takes input data and produces a fixed-size, 256-bit (32-byte) hash value.

SHA-256 is widely used for data integrity, digital signatures, and security applications.

Let's take a look at a few examples of how to generate a SHA-256 in Java.


Example:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class JavaSHA256HashExample {

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

        String algorithm = "SHA-256";
        String inputMessage = "Code2care";
        MessageDigest sha256MessageDigest = MessageDigest.getInstance(algorithm);
        byte[] hashBytes = sha256MessageDigest.digest(inputMessage.getBytes());

        StringBuilder hexString = new StringBuilder();
        for (byte b : hashBytes) {
            hexString.append(String.format("%02x", b));
        }

        System.out.println("Message:" + inputMessage);
        System.out.println("SHA-256 Hash: " + hexString.toString());
    }
}

Output:

Message:Code2care
SHA-256 Hash: 96111e521eec4620d6da2006d39891a7c8099dba6861baca73a11037a9bf63bb

We have made use of the builtin MessageDigest class from java.security API and not used any 3rd party libraries.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap