正在加载,请稍候…

SHA-256 Hash: How It Works, How to Generate, and When to Use It

Learn what SHA-256 is, how it produces a hash, use cases from file verification to HMAC signing, and how to generate SHA-256 hashes online or in code.

What Is SHA-256?

SHA-256 (Secure Hash Algorithm 256-bit) is a cryptographic hash function from the SHA-2 family, standardized by NIST in 2001. It takes any input — a byte, a file, an entire database dump — and produces a fixed-length 256-bit (32-byte) output, usually displayed as 64 hexadecimal characters.

Input:  "hello"
Output: 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Input:  "hello." (one extra character)
Output: 0d9b02b1b3cd52e9fcf5db5c5e38cfe97c97a4e8f0d4fba7fee7b5b5b5b60a00

The second output is completely different despite a tiny input change — this is the avalanche effect, a core property of good hash functions.

Core Properties of SHA-256

Deterministic: Same input always produces the same output. You can verify a hash without re-downloading the original file.

One-way (preimage resistant): You cannot reverse a hash back to the original input by design. Given the output, finding any input that produces it requires astronomical computation.

Collision resistant: It's computationally infeasible to find two different inputs with the same hash output. SHA-256 has had no known practical collisions (unlike MD5 and SHA-1, which are broken in this regard).

Fixed output size: Whether you hash a single character or a 100GB video file, the output is always 256 bits.

Fast: SHA-256 can compute billions of hashes per second on modern hardware. This is great for file verification but makes it unsuitable for password hashing (use bcrypt, Argon2, or PBKDF2 instead).

How SHA-256 Works

SHA-256 uses a Merkle-Damgård construction:

  1. Padding: Input is padded to a multiple of 512 bits by appending a 1-bit, zeros, then a 64-bit length field
  2. Parsing: Padded input is divided into 512-bit (64-byte) blocks
  3. Compression: Each block is processed through 64 rounds of mixing with constants derived from the fractional parts of cube roots of the first 64 primes
  4. Chaining: Each block's output feeds into the next block as the initial state
  5. Final hash: The 256-bit state after the last block is the hash

This design means SHA-256 is sequential — processing block N depends on the output of block N-1.

Generating SHA-256 in Code

JavaScript (Browser and Node.js)

// Browser — Web Crypto API (built-in, no dependencies)
async function sha256(message) {
  const encoder = new TextEncoder();
  const data = encoder.encode(message);
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

const hash = await sha256('hello world');
// => b94d27b9934d3e08a52e52d7da7dabfac484efe04294e576a55df5b2b1e63d4c
// Node.js — built-in crypto module
const crypto = require('crypto');

const hash = crypto.createHash('sha256').update('hello world').digest('hex');

Python

import hashlib

# Hash a string
h = hashlib.sha256(b'hello world').hexdigest()
print(h)  # b94d27b9934d3e08a52e52d7da7dabfac484efe04294e576a55df5b2b1e63d4c

# Hash a file (streaming, handles large files)
def sha256_file(filepath):
    h = hashlib.sha256()
    with open(filepath, 'rb') as f:
        for chunk in iter(lambda: f.read(8192), b''):
            h.update(chunk)
    return h.hexdigest()

print(sha256_file('/path/to/file'))

Shell (Linux/macOS)

# Hash a string
echo -n "hello world" | sha256sum

# Hash a file
sha256sum filename.iso

# macOS
shasum -a 256 filename.iso

Go

import (
    "crypto/sha256"
    "fmt"
)

h := sha256.Sum256([]byte("hello world"))
fmt.Printf("%x\n", h)

Common Use Cases

1. File Integrity Verification

Software publishers post SHA-256 checksums alongside downloads. After downloading, verify the file wasn't corrupted or tampered with:

sha256sum ubuntu-24.04-desktop-amd64.iso
# should match the checksum on ubuntu.com

2. HMAC Signatures

HMAC-SHA256 (Hash-based Message Authentication Code) verifies that a message was sent by someone with a shared secret key. Used by GitHub webhooks, AWS Signature V4, JWT HS256.

const crypto = require('crypto');

// Sign
const signature = crypto
  .createHmac('sha256', 'your-secret-key')
  .update(JSON.stringify(payload))
  .digest('hex');

// Verify (timing-safe comparison)
const expected = crypto
  .createHmac('sha256', 'your-secret-key')
  .update(JSON.stringify(incomingPayload))
  .digest('hex');

const isValid = crypto.timingSafeEqual(
  Buffer.from(signature, 'hex'),
  Buffer.from(expected, 'hex')
);

3. Content-Addressable Storage

Git uses SHA-1 (and is migrating to SHA-256) to address objects — every commit, tree, and blob has a hash that uniquely identifies its content. Identical content always gets the same hash, enabling deduplication.

4. Data Deduplication

Before storing an uploaded file, hash it and check if the hash already exists in storage. If it does, store a reference instead of a duplicate.

def store_file(data: bytes) -> str:
    file_hash = hashlib.sha256(data).hexdigest()
    if not storage.exists(file_hash):
        storage.save(file_hash, data)
    return file_hash  # return hash as file ID

5. Deterministic IDs

SHA-256 creates stable, collision-resistant IDs from content — useful for caching, deduplication, and distributed systems where you need to derive an ID without a central counter.

6. Commitment Schemes

In protocols where one party commits to a value without revealing it (e.g., auctions, coin flips), they publish sha256(value + nonce). Later they reveal the value and nonce; anyone can verify the commitment.

SHA-256 vs Other Hash Functions

Function Output Speed Collision Status Password Hashing
MD5 128-bit Very fast Broken ❌ Never use
SHA-1 160-bit Fast Broken (SHAttered) ❌ Never use
SHA-256 256-bit Fast Secure ❌ Too fast
SHA-512 512-bit Fast Secure ❌ Too fast
bcrypt varies Slow by design N/A ✅ Use for passwords
Argon2id varies Slow + memory-hard N/A ✅ Recommended

Never use SHA-256 for password storage. Its speed is a liability — an attacker with a GPU can try billions of passwords per second. Use bcrypt, Argon2id, or PBKDF2 instead.

Frequently Asked Questions

Can two files have the same SHA-256 hash? Theoretically yes (birthday paradox), but no practical collision has been found. The probability is 1/2^128 for any two random inputs — effectively impossible.

Is SHA-256 the same as SHA-2? SHA-2 is a family. SHA-256 is one member (256-bit output). Others: SHA-224, SHA-384, SHA-512, SHA-512/224, SHA-512/256.

Should I use SHA-256 or SHA-512? SHA-512 has a larger output and is slightly faster on 64-bit systems. Choose SHA-256 for compatibility and standard use cases. Use SHA-512 when 256 bits of collision resistance isn't enough (e.g., digital signatures for very long-lived documents).

Is SHA-256 used in Bitcoin? Yes. Bitcoin uses SHA-256 twice (double-SHA256) for mining (proof of work) and transaction IDs.

→ Generate SHA-256 and other hashes instantly with the Hash Text Tool.