5

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

 3 years ago
source link: https://marco.dev/blockchain-256/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The hash SHA-256 for Blockchain

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.

Javascript

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 java.security 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");
    messageDigest.update(textToHash.getBytes(Charset.defaultCharset()));

    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) {
        hexText
        .append(HEXADECIMALS.charAt((byteElement & 0xF0) >> 4))
        .append(HEXADECIMALS.charAt((byteElement & 0x0F)));     
    }
    
    return hexText.toString();
}

Example: The string test is converted in 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08.

Author

Marco Molteni

Marco Molteni Blog


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK