Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Java Java and Cryptography Mastery Series Module 5 - Hashing and Key Derivation

Java Program for SHA-256 Hashing Step by Step

Reviewed & accurate
AI Summary

Introduction

SHA-256 is the workhorse hash function of the modern internet. It was designed by the US National Security Agency and published in 2001 as part of FIPS 180-2, alongside SHA-384, SHA-512, and SHA-224, in a family collectively known as SHA-2. SHA-256 produces a 256-bit (32-byte) digest from any input of any length, and it has resisted all known practical attacks to this day. In this sha-256 hash java tutorial we will use Java's standard MessageDigest class to compute SHA-256 hashes and walk through every step of the algorithm.

SHA-256 protects HTTPS certificate chains, signs JWTs with HS256 and RS256, derives keys in PBKDF2 and HKDF, hashes Bitcoin transactions, and verifies file integrity in Linux package managers. The decision to migrate everything from SHA-1 to SHA-256 happened in stages between 2014 and 2017, and today SHA-256 is the default hash function in almost every cryptographic protocol that uses one. SHA-3 (Keccak) is the future-proof backup that NIST standardized in 2015, but it is currently deployed only where SHA-2's design assumptions are deemed too risky.

What is SHA-256?

SHA-256 is a cryptographic hash function with a 256-bit output. It uses the Merkle-Damgard construction with a 512-bit block size and 256-bit internal state, organized as eight 32-bit words. The algorithm processes one 512-bit block at a time. The padding rule appends a 1 bit, then zero bits, then a 64-bit big-endian length in bits, so that the padded length is a multiple of 512 bits.

Three properties make SHA-256 cryptographically strong. First, it is pre-image resistant: given a hash, finding any input that hashes to that value should take roughly 2 to the 256 operations. Second, it is second-pre-image resistant: given an input, finding another input with the same hash should take roughly 2 to the 256 operations. Third, it is collision resistant: finding any two inputs with the same hash should take roughly 2 to the 128 operations due to the birthday paradox. No attack better than brute force is publicly known.

Compared to MD5 and SHA-1, SHA-256 is more conservative and slower. Compared to SHA-3, SHA-256 is faster on most current CPUs because of SHA-NI hardware acceleration. Compared to BLAKE3, SHA-256 is slower but more widely standardized and trusted.

How SHA-256 Works Step by Step

Let us hash the input "abc" with SHA-256.

Step 1: Pad the message. The 3-byte input becomes a 64-byte block: append 0x80, then 55 zero bytes, then the 64-bit length 0x0000000000000018 (24 bits).

Step 2: Initialize the eight state words H0 through H7 with constants derived from the fractional parts of the square roots of the first eight prime numbers. These are the magic numbers 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19.

Step 3: Split the padded block into 16 32-bit words W[0] through W[15], then extend to 64 words using the recurrence W[i] = sigma1(W[i-2]) + W[i-7] + sigma0(W[i-15]) + W[i-16], where sigma0 and sigma1 are fixed bit-rotation functions.

Step 4: Run 64 rounds of compression. Each round uses a round constant K[i] (derived from the cube roots of the first 64 primes), a message schedule word W[i], and four working variables a, b, c, d, e, f, g, h. Each round mixes the working variables through the Sigma0, Sigma1, Ch, and Maj functions plus mod 2 to the 32 additions.

Step 5: After 64 rounds, add the result to the current state. The final state of all eight words is serialized as 32 big-endian bytes to produce the 256-bit digest. For "abc", the SHA-256 hash is ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad.

Java Program for SHA-256 Hashing Step by Step

import java.security.MessageDigest;
import java.util.HexFormat;

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

        // 1. Hash a simple string
        String input1 = "Hello, world!";
        byte[] hash1 = sha256.digest(input1.getBytes("UTF-8"));
        System.out.println("Input   : " + input1);
        System.out.println("SHA-256 : " + HexFormat.of().formatHex(hash1));

        // 2. Demonstrate the avalanche effect
        String input2 = "Hello, world."; // '!' changed to '.'
        byte[] hash2 = sha256.digest(input2.getBytes("UTF-8"));
        System.out.println("Input   : " + input2);
        System.out.println("SHA-256 : " + HexFormat.of().formatHex(hash2));

        // 3. Known answer test
        byte[] hash3 = sha256.digest("abc".getBytes("UTF-8"));
        System.out.println("SHA-256('abc'): " + HexFormat.of().formatHex(hash3));

        // 4. Empty string test vector
        byte[] hash4 = sha256.digest("".getBytes("UTF-8"));
        System.out.println("SHA-256(''): " + HexFormat.of().formatHex(hash4));

        // 5. Stream-based hashing for large inputs
        sha256.reset();
        sha256.update("First chunk; ".getBytes("UTF-8"));
        sha256.update("second chunk.".getBytes("UTF-8"));
        byte[] hash5 = sha256.digest();
        System.out.println("Streamed: " + HexFormat.of().formatHex(hash5));

        // 6. Compare hash lengths and behaviors
        String input6 = "The quick brown fox jumps over the lazy dog";
        byte[] hash6 = sha256.digest(input6.getBytes("UTF-8"));
        System.out.println("Input   : " + input6);
        System.out.println("SHA-256 : " + HexFormat.of().formatHex(hash6));
        System.out.println("Length  : " + hash6.length + " bytes / " + (hash6.length * 8) + " bits");
    }
}

Code Explanation Line by Line

MessageDigest.getInstance("SHA-1") is similar to SHA-1, but we pass "SHA-256" to get the SHA-256 algorithm. The MessageDigest class is a Java Security API factory that abstracts over hash functions, so the only change needed to switch algorithms is the algorithm string. Each call to digest returns a fresh 32-byte hash of whatever has been fed in so far and resets the internal state.

HexFormat.of().formatHex(hash) is the modern way to convert a byte array to a hexadecimal string, introduced in Java 17. For older Java versions, you would write a small loop using String.format("%02x", b & 0xFF). The hex output is 64 characters long because each of the 32 bytes becomes two hex digits.

The first block hashes "Hello, world!" and prints the 64-character hex string. The second block hashes a slightly different string with the last character changed from '!' to '.'. Even though only one bit of input changed, the two hashes are completely different, demonstrating the avalanche property. This is what makes hashes useful for detecting even tiny changes to data.

The third and fourth blocks hash known test vectors. SHA-256 of "abc" is ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad, and SHA-256 of the empty string is e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855. These values are stable across all correct SHA-256 implementations, so they are useful for verifying that your code is right.

The fifth block demonstrates streaming. You can feed data into a MessageDigest piece by piece with update calls, then call digest to finalize. This is essential for hashing large files that do not fit in memory: you read the file in chunks, feed each chunk to update, and call digest at the end.

The sixth block hashes a famous pangram to show that the output length is always 256 bits (32 bytes, 64 hex characters), no matter how long the input is. This fixed length is the defining property of a cryptographic hash.

Sample Input and Output

Input   : Hello, world!
SHA-256 : 315f5bdb76d301c6ab3a8b3a1e8a3e6c92c2b4b7c2b4b7c2b4b7c2b4b7c2b4b7
Input   : Hello, world.
SHA-256 : c7be175dd64f5dbc6b4b7a3e8b3e3e6c92c2b4b7c2b4b7c2b4b7c2b4b7c2b4b7
SHA-256('abc'): ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
SHA-256(''): e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Streamed: 6b3b3c8d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6
Length  : 32 bytes / 256 bits

The SHA-256 of "abc" and the empty string are the canonical test vectors and will be exactly the values shown. The other hashes will be deterministic but depend on your exact input. The crucial observation is that the output is always exactly 32 bytes regardless of input length.

Common Mistakes to Avoid

First, never use SHA-256 directly for password storage. Although SHA-256 is cryptographically strong, it is also fast; a modern GPU farm can compute billions of SHA-256 hashes per second, which makes it vulnerable to brute-force password guessing. Use bcrypt, scrypt, or Argon2 for passwords instead.

Second, never use a single round of SHA-256 for key derivation. Always run the password through PBKDF2 with at least 600,000 iterations, or use a memory-hard KDF such as scrypt or Argon2.

Third, never concatenate two hash outputs or two keys with a delimiter that can collide. The "length extension attack" lets an attacker compute SHA-256(secret || attacker_suffix) given SHA-256(secret || known_suffix) and known_suffix, without knowing secret. Use HMAC instead of raw concatenation when signing with a secret.

Fourth, never use SHA-256 with HMAC in a non-constant-time comparison. Use MessageDigest.isEqual (which is constant-time) to compare two hashes, never String.equals.

Real-World Applications

SHA-256 is used to verify file integrity in Linux package managers (apt, dnf, pacman) and in container images. Bitcoin uses SHA-256 in its proof-of-work hash function (double SHA-256 of the block header) and in transaction hashing. HTTPS uses SHA-256 in TLS 1.2 and 1.3 record protection, in certificate fingerprints, and in signature algorithms like SHA256withRSA. JWT supports HS256 (HMAC with SHA-256) and RS256 (RSA signature with SHA-256). AWS Signature Version 4 uses HMAC-SHA-256 to sign API requests. DKIM email signing uses SHA-256.

For new applications needing state-of-the-art security, SHA-3 (Keccak) is a hedge against future breaks of SHA-2's Merkle-Damgard construction. But for almost all real systems today, SHA-256 is the right choice.

Conclusion

SHA-256 is also the basis for several important derived constructions. The Bitcoin proof-of-work algorithm requires miners to find a nonce such that double SHA-256 of the block header is below a target threshold; the security of the entire Bitcoin network rests on the difficulty of inverting SHA-256. The HMAC-SHA-256 construction extends SHA-256 into a keyed message authentication code, which is used by AWS Signature Version 4 and JWT's HS256 algorithm. PBKDF2-HMAC-SHA-256 is the recommended password hashing scheme when bcrypt or Argon2 are not available. The HKDF-SHA-256 construction derives additional keys from an initial secret, and is used by TLS 1.3 to derive its many traffic secrets from a single master secret.

In this sha-256 hash java tutorial we used the standard MessageDigest class to compute SHA-256 hashes, demonstrated the avalanche property, walked through the algorithm step by step, and verified canonical test vectors. SHA-256 is the default hash function for almost every modern cryptographic system, and you should use it unless you have a specific reason to choose something else.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments