How To Generate SHA256 Hash in Java

In cryptography, SHA (Secure Hash Algorithm) is a hash function which generates a unique value for a given data. This unique value (known as hash) has the following properties,

  • It is impossible to arrive at the original message from hash.
  • Two different messages practically cannot have the same hash.
  • Modifying message changes the corresponding hash.
  • It is easy to generate the hash value with the above properties.

These one way hash values are the fundamental building blocks of modern cryptography. One of the popular algorithms for hash generation is SHA. There are a number of variants of SHA algorithms such as SHA-1 and SHA-256. Out of these SHA-1 was the most popular until security vulnerabilities were found in them. Nowadays the recommended hash function for digital security (digital signatures, security certificates etc.) is SHA-256.

The following program shows how to generate SHA256 hash in Java. This program uses the built-in class java.security.MessageDigest for creating the SHA256 hash. Note that the hash output generated is binary data and hence if you try to convert it directly to String, you will get unprintable weird looking characters. Hence usually the bytes are converted to a readable hexadecimal form so that hash values can be printed or send over email. I have used javax.xml.bind.DatatypeConverter built-in class to convert byte array to a hexadecimal string.

import java.security.MessageDigest;
import java.util.Scanner;
import javax.xml.bind.DatatypeConverter;

/**
 * Demonstrates how to generate SHA256 hash in Java
 * @author JJ
 */
public class SHA256InJava {

    public static void main(String[] args) {
        Scanner sn = new Scanner(System.in);
        System.out.print("Please enter data for which SHA256 is required:");
        String data = sn.nextLine();
        
        SHA256InJava sj = new SHA256InJava();
        String hash = sj.getSHA256Hash(data);
        System.out.println("The SHA256 (hexadecimal encoded) hash is:"+hash);
    }

    /**
     * Returns a hexadecimal encoded SHA-256 hash for the input String.
     * @param data
     * @return 
     */
    private String getSHA256Hash(String data) {
        String result = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(data.getBytes("UTF-8"));
            return bytesToHex(hash); // make it printable
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
    
    /**
     * Use javax.xml.bind.DatatypeConverter class in JDK to convert byte array
     * to a hexadecimal string. Note that this generates hexadecimal in upper case.
     * @param hash
     * @return 
     */
    private String  bytesToHex(byte[] hash) {
        return DatatypeConverter.printHexBinary(hash);
    }
}