Blockchain: How to generate a SHA-256 hash with Java

Bitcoin and many blockchains use the cryptographic hash function SHA-256 to hash the blocks.

On the other side, Ethereum uses his own algorithm : Ethash and the informations of this post are not useful for Ethereum.

Here you can find more information about the hash function.


In Javascript and Typescript you can use the library crypto-js to create a new hash.


In Java we have the feature (class ;)) included in the package: MessageDigest

The following code generate a SHA-256 byte array :

public static byte[] generateSHA256(String textToHash) 
    throws NoSuchAlgorithmException { 
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); 
    return messageDigest.digest(); 

To see the result printed correctly we ha to convert the array of bytes in hexadecimals:

private static final String HEXADECIMALS = "0123456789abcdef"; 
public static String convertByteArrayToHexString(byte[] byteArray) { 
    final StringBuilder hexText = new StringBuilder(2 * byteArray.length); 
    for (byte byteElement : byteArray) { 
        .append(HEXADECIMALS.charAt((byteElement & 0xF0) >> 4)) 
        .append(HEXADECIMALS.charAt((byteElement & 0x0F)));      
    return hexText.toString(); 

The string test is converted in 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08.

WebApp built by Marco using SpringBoot, Java 17, Mustache, Markdown and in Azure