SHA-256 stands for Secure Hash Algorithm 256-bit. It is part of the SHA-2 family developed by the National Security Agency (NSA) and published by NIST (National Institute of Standards and Technology) in 2001.
SHA-256:
- Produces a fixed 256-bit (32-byte) hash value.
- Is deterministic – same input will always produce the same output.
- Is one-way – you can’t reverse the hash to get the original input.
- Is collision-resistant – it’s computationally hard to find two inputs that hash to the same output.
- Is used in digital signatures, blockchain (e.g., Bitcoin), certificate verification, password hashing, and more.
How SHA-256 Works – Conceptually
SHA-256 takes an input (of any size) and processes it in the following steps:
1. Padding the Input
- The original message is padded with a
1
bit followed by0
s until its length is 64 bits short of a multiple of 512. - The last 64 bits are used to store the original length of the message in binary.
2. Parsing the Message
- The padded message is divided into 512-bit blocks.
3. Message Schedule
- Each 512-bit block is split into 16 words of 32 bits each.
- These are expanded to 64 32-bit words using logical operations.
4. Compression Function
- Uses 8 initial hash values (32-bit constants) and 64 round constants.
- Performs 64 rounds of processing per block using bitwise operations, additions, and logical functions like AND, OR, XOR, and ROTATE.
5. Output
- After processing all blocks, the final 256-bit hash is produced.
SHA-256 in Practice
Let’s see how to use SHA-256 in code.
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class SHA256Example { public static String toHex(byte[] hash) { StringBuilder hexString = new StringBuilder(); for (byte b : hash) hexString.append(String.format("%02x", b)); return hexString.toString(); } public static String sha256(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8)); return toHex(hash); } public static void main(String[] args) throws NoSuchAlgorithmException { String input = "hello world"; String hash = sha256(input); System.out.println("SHA-256 hash: " + hash); } }
Applications of SHA-256
1. Blockchain
- Bitcoin uses SHA-256 for block hashing and mining.
2. Password Hashing
- Storing hashed passwords instead of plain text.
- Used with salt to prevent dictionary attacks.
3. Digital Signatures
- Ensures data integrity and authenticity.
4. Checksums
- File integrity verification using SHA-256 hash.
Security Considerations
- SHA-256 is currently not broken, but slower than some newer algorithms like BLAKE2.
- Not recommended for passwords without salting and key stretching – use
bcrypt
,scrypt
, orPBKDF2
instead. - Suitable for digital signatures, hash-based integrity checks, and blockchain.