Calculate Double-SHA256 Hash with Java

This section describes how to calculate Double-SHA256 hash with Java.

If you are a Java developer and want to calculating SHA256 hash, you need to get familiar with two classes:

Here is my Java program to perform SHA256 hash and Double-SHA256 hash on 3 test vectors:

// DoubleSHA256TestVectors.java
// Copyright (c) 2018, HerongYang.com, All Rights Reserved.

import java.security.*;
import javax.xml.bind.DatatypeConverter;

public class DoubleSHA256TestVectors {
  public static void main(String [] args) throws Exception {
    MessageDigest md = MessageDigest.getInstance("SHA-256");

    String hex = "616263";
    System.out.println("\nTest 1: 'abc' or '0x"+hex+"'");
    byte[] bin = DatatypeConverter.parseHexBinary(hex);
    md.reset();
    byte[] hash = md.digest(bin);
    md.reset();
    byte[] hash2 = md.digest(hash);
    System.out.println("SHA256:\n   "
       +DatatypeConverter.printHexBinary(hash));
    System.out.println("Double-SHA256:\n   "
       +DatatypeConverter.printHexBinary(hash2));

    hex = "00";
    System.out.println("\nTest 2: null or '0x"+hex+"'");
    bin = DatatypeConverter.parseHexBinary(hex);
    md.reset();
    hash = md.digest(bin);
    md.reset();
    hash2 = md.digest(hash);
    System.out.println("SHA256:\n   "
       +DatatypeConverter.printHexBinary(hash));
    System.out.println("Double-SHA256:\n   "
       +DatatypeConverter.printHexBinary(hash2));
  }  
}

The output looks good. SHA256 values match well with tests published on the Internet.

C:\>javac DoubleSHA256TestVectors.java

C:\>java DoubleSHA256TestVectors

Test 1: 'abc' or '0x616263'
SHA256:
   BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD
Double-SHA256:
   4F8B42C22DD3729B519BA6F68D2DA7CC5B2D606D05DAED5AD5128CC03E6C6358

Test 2: null or '0x00'
SHA256:
   6E340B9CFFB37A989CA544E6BB780A2C78901D3FB33738768511A30617AFA01D
Double-SHA256:
   1406E05881E299367766D313E26C05564EC91BF721D31726BD6E46E60689539A

Table of Contents

 About This Book

 Introduction of Bitcoin

 Bitcoin Blockchain

 Bitcoin Wallet

 Bitcoin Core

 Bitcoin Transaction

 Bitcoin-Qt - Bitcoin Core GUI

 Bitcoin Mining

 Bitcoin Consensus Rules

Bitcoin Block Data Structure

 Data Components of Bitcoin Block

 Data Properties of Bitcoin Block

 Merkle Root of Bitcoin Block

 Calculate Double-SHA256 Hash with Python

 Verify Merkle Root of 2 Transactions

 Verify Merkle Root of 7 Transactions

 Data Structure of Bitcoin Block

 "getblock blockhash 0" - Serialized Hex Block Data

 Block Hash Calculation Algorithm

 Block Hash Calculation in Python

Calculate Double-SHA256 Hash with Java

 Bitcoin Transaction Data Structure

 Bitcoin Blockchain APIs

 Copay - Bitcoin Wallet

 Archived Tutorials

 References

 Full Version in PDF/EPUB