What is SHA-256?
SHA-256 (Secure Hash Algorithm 256-bit) is a cryptographic hash function that belongs to the SHA-2 family, designed by the U.S. National Security Agency (NSA) and published in 2001. It's one of the most widely used hash functions in modern cryptography.
How SHA-256 Works
SHA-256 uses the Merkle-Damgård construction with a compression function based on the Davies-Meyer scheme:
- Message Preparation: Input is padded to a multiple of 512 bits with length encoding
- Initial Hash Values: Eight 32-bit hash values are initialized using square roots of primes
- Message Schedule: Each 512-bit block is expanded into 64 32-bit words
- Compression Function: 64 rounds of operations using bitwise functions and modular addition
- Final Hash: The resulting 256-bit hash is output as 64 hexadecimal characters
Core Operations:
- Ch(x,y,z): (x ∧ y) ⊕ (¬x ∧ z)
- Maj(x,y,z): (x ∧ y) ⊕ (x ∧ z) ⊕ (y ∧ z)
- Σ0(x): ROTR2(x) ⊕ ROTR13(x) ⊕ ROTR22(x)
- Σ1(x): ROTR6(x) ⊕ ROTR11(x) ⊕ ROTR25(x)
Key Features
Secure
No known practical attacks
Fast
Efficient on modern hardware
Fixed Size
Always 256 bits (64 hex chars)
Standardized
FIPS PUB 180-4 standard
SHA-2 Family Comparison
| Algorithm |
Output Size |
Security Level |
Performance |
| SHA-224 |
224 bits |
112 bits |
Fast |
| SHA-256 |
256 bits |
128 bits |
Fast |
| SHA-384 |
384 bits |
192 bits |
Moderate |
| SHA-512 |
512 bits |
256 bits |
Moderate |
JavaScript
// Using Web Crypto API (modern browsers)
async function sha256(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
// Usage
sha256('Hello World').then(hash => {
console.log(hash); // a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b4f87e8ce45d5331a0
});
// Using crypto-js library
const CryptoJS = require('crypto-js');
const hash = CryptoJS.SHA256('Hello World').toString();
// Node.js built-in
const crypto = require('crypto');
const hash = crypto.createHash('sha256')
.update('Hello World')
.digest('hex');
Python
import hashlib
# Hash a string
text = "Hello World"
hash_object = hashlib.sha256(text.encode())
hex_dig = hash_object.hexdigest()
print(hex_dig) # a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b4f87e8ce45d5331a0
# Hash a file
def hash_file(filename):
h = hashlib.sha256()
with open(filename, 'rb') as file:
while chunk := file.read(8192):
h.update(chunk)
return h.hexdigest()
# HMAC-SHA256
import hmac
key = b'secret_key'
message = b'Hello World'
hmac_hash = hmac.new(key, message, hashlib.sha256).hexdigest()
PHP
// Hash a string
$text = "Hello World";
$hash = hash('sha256', $text);
echo $hash; // a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b4f87e8ce45d5331a0
// Hash with binary output
$binaryHash = hash('sha256', $text, true);
// Hash a file
$fileHash = hash_file('sha256', 'file.txt');
// HMAC-SHA256
$key = 'secret_key';
$hmac = hash_hmac('sha256', $text, $key);
Command Line
# Linux/Mac
echo -n "Hello World" | sha256sum
# a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b4f87e8ce45d5331a0 -
# Mac alternative
echo -n "Hello World" | shasum -a 256
# Hash a file
sha256sum file.txt
# Windows PowerShell
Get-FileHash file.txt -Algorithm SHA256
# OpenSSL
echo -n "Hello World" | openssl dgst -sha256
Common Use Cases
Digital Signatures
Used in SSL/TLS certificates, code signing, and document signing
Data Integrity
Verify file downloads, detect tampering, and ensure data consistency
Password Storage
As part of key derivation functions (not directly)
Blockchain
Bitcoin and many cryptocurrencies use SHA-256 for mining
Unique Identifiers
Generate content-based IDs for deduplication
API Security
Request signing and webhook verification
Real-World Examples
1. File Integrity Verification
// Generate checksum for download verification
const fileBuffer = await fetch('https://example.com/file.zip').then(r => r.arrayBuffer());
const hashBuffer = await crypto.subtle.digest('SHA-256', fileBuffer);
const checksum = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
// Verify against published checksum
if (checksum === publishedChecksum) {
console.log('File integrity verified!');
}
2. API Request Signing
import hashlib
import hmac
import time
# Create signed API request
api_key = "your_api_key"
api_secret = "your_api_secret"
timestamp = str(int(time.time()))
method = "POST"
path = "/api/v1/orders"
body = '{"symbol":"BTCUSD","size":100}'
# Create signature
message = timestamp + method + path + body
signature = hmac.new(
api_secret.encode(),
message.encode(),
hashlib.sha256
).hexdigest()
# Add to request headers
headers = {
'API-KEY': api_key,
'API-TIMESTAMP': timestamp,
'API-SIGNATURE': signature
}
Security Properties
One-Way Function
It's computationally infeasible to find the input from the hash output
Deterministic
Same input always produces the same hash output
Avalanche Effect
Small changes in input produce drastically different outputs
Collision Resistant
Extremely difficult to find two different inputs with the same hash
Best Practices
DO
- Use SHA-256 for digital signatures and certificates
- Verify file integrity with SHA-256 checksums
- Use HMAC-SHA256 for message authentication
- Combine with salt for password hashing (use PBKDF2/bcrypt/scrypt)
- Use for blockchain and cryptocurrency applications
DON'T
- Use SHA-256 directly for password storage
- Assume SHA-256 provides encryption (it's one-way)
- Use MD5 or SHA-1 for new applications
- Implement your own SHA-256 (use standard libraries)
- Use for small hash tables (overkill, use CRC32 or similar)
Performance Considerations
SHA-256 is optimized for 32-bit operations and performs well on most modern hardware. For reference:
- Modern CPU: ~100-500 MB/s (software implementation)
- Hardware acceleration: ~1-10 GB/s (with AES-NI or similar)
- GPU implementation: Can achieve even higher throughput
Future Considerations
While SHA-256 is currently secure, quantum computers may pose a threat in the future. SHA-256 provides 128-bit security against quantum attacks (using Grover's algorithm), which is still considered secure for the foreseeable future. For ultra-high security requirements, consider SHA-3 or larger SHA-2 variants like SHA-512.
SHA-256 Hash Examples
| Input |
SHA-256 Hash |
| "" (empty string) |
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 |
| "Hello World" |
a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e |
| "The quick brown fox jumps over the lazy dog" |
d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592 |
Industry Applications
Bitcoin & Blockchain
SHA-256 is the proof-of-work algorithm for Bitcoin mining and block hashing
SSL/TLS Certificates
Used in X.509 certificates for secure web communications
Digital Signatures
Core component of DSA, ECDSA, and RSA signature schemes
Password Hashing
Used with PBKDF2 for secure password storage
HMAC Authentication
HMAC-SHA256 for message authentication codes
File Integrity
Verify downloads and detect file tampering
Frequently Asked Questions
Q: Is SHA-256 quantum-resistant?
A: SHA-256 offers 128-bit security against quantum attacks using Grover's algorithm. While not fully quantum-resistant, this is still considered secure for the foreseeable future.
Q: How long does SHA-256 take to compute?
A: On modern hardware, SHA-256 can process 100-500 MB/s in software, and over 1 GB/s with hardware acceleration. For small inputs, computation is essentially instantaneous.
Q: Can SHA-256 be reversed?
A: No, SHA-256 is a one-way function. It's computationally infeasible to find the input from the hash output, even with quantum computers.
Q: SHA-256 vs SHA-512: Which is better?
A: SHA-512 offers higher security (256-bit vs 128-bit against quantum attacks) and is faster on 64-bit systems. SHA-256 is more widely supported and sufficient for most applications.
Q: Is SHA-256 suitable for password hashing?
A: SHA-256 alone is too fast for password hashing. Use it with PBKDF2 (with high iterations), or better yet, use dedicated password hashing functions like bcrypt or Argon2.
Technical Specifications
| Digest Size: |
256 bits (32 bytes, 64 hex chars) |
| Block Size: |
512 bits (64 bytes) |
| Word Size: |
32 bits |
| Rounds: |
64 |
| Security Level: |
128 bits (quantum), 256 bits (classical) |
| Published: |
2001 (FIPS PUB 180-2) |
| Constants: |
First 32 bits of fractional parts of cube roots of first 64 primes |