SHA256
hash length
cryptography
hashing algorithm
data security
How long is the SHA256 hash?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
## Introduction
A SHA-256 hash is always exactly **256 bits** long. That is **32 bytes**, or **64 hexadecimal characters**. No matter whether you hash a single letter or an entire database backup, the output is always the same fixed length. This predictability is a fundamental property of cryptographic hash functions.
## SHA-256 Length in Every Format
| Representation | Length | Example |
|---------------|--------|---------|
| Bits | 256 | `1011101001...` (256 digits) |
| Bytes | 32 | 32 raw bytes |
| Hexadecimal | 64 characters | `e3b0c44298fc1c149afbf4c8996fb92427ae41e4...` |
| Base64 | 44 characters | `47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hS...` |
| Base58 (Bitcoin) | 43-44 characters | Variable due to leading-zero encoding |
The hexadecimal format (64 characters) is by far the most common. When someone says "a SHA-256 hash," they almost always mean the 64-character hex string.
### Why 64 hex characters?
Each hexadecimal digit represents 4 bits. So $256 \div 4 = 64$ hex digits. Each pair of hex digits represents one byte, giving $64 \div 2 = 32$ bytes.
## Generating SHA-256 Hashes
### Command line
```bash
# Linux / macOS
echo -n "Hello, World!" | sha256sum
# dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f -
# macOS (alternative)
echo -n "Hello, World!" | shasum -a 256
# Windows PowerShell
(Get-FileHash -InputStream ([System.IO.MemoryStream]::new([System.Text.Encoding]::UTF8.GetBytes("Hello, World!"))) -Algorithm SHA256).Hash
```
Note the `-n` flag with `echo`. Without it, `echo` appends a newline character, which changes the hash entirely.
### Python
```python
import hashlib
# Hash a string
message = "Hello, World!"
hash_hex = hashlib.sha256(message.encode()).hexdigest()
print(hash_hex)
# dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
print(len(hash_hex)) # 64
# Hash raw bytes
hash_bytes = hashlib.sha256(message.encode()).digest()
print(len(hash_bytes)) # 32
```
### JavaScript (Node.js)
```javascript
const crypto = require("crypto");
const hash = crypto.createHash("sha256").update("Hello, World!").digest("hex");
console.log(hash);
// dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
console.log(hash.length); // 64
```
### JavaScript (Browser)
```javascript
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));
return hashArray.map(b => b.toString(16).padStart(2, "0")).join("");
}
sha256("Hello, World!").then(console.log);
// dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
```
### Java
```java
import java.security.MessageDigest;
public class SHA256Example {
public static void main(String[] args) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest("Hello, World!".getBytes("UTF-8"));
StringBuilder hex = new StringBuilder();
for (byte b : hash) {
hex.append(String.format("%02x", b));
}
System.out.println(hex.toString());
// dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
System.out.println(hex.length()); // 64
}
}
```
### Hashing a file
```bash
# Linux
sha256sum largefile.zip
# e3b0c44298fc1c14... largefile.zip
# macOS
shasum -a 256 largefile.zip
# Windows PowerShell
Get-FileHash largefile.zip -Algorithm SHA256
```
## Comparing SHA-256 to Other Hash Functions
| Algorithm | Output bits | Hex length | Relative speed | Security status |
|-----------|-----------|------------|-----------------|-----------------|
| MD5 | 128 | 32 chars | Fastest | Broken (collisions found) |
| SHA-1 | 160 | 40 chars | Fast | Deprecated (collisions found) |
| SHA-224 | 224 | 56 chars | Same as SHA-256 | Secure |
| **SHA-256** | **256** | **64 chars** | **Baseline** | **Secure** |
| SHA-384 | 384 | 96 chars | Same as SHA-512 | Secure |
| SHA-512 | 512 | 128 chars | Faster on 64-bit CPUs | Secure |
| SHA3-256 | 256 | 64 chars | Slower than SHA-256 | Secure |
| BLAKE2b | 256 (configurable) | 64 chars | Faster than SHA-256 | Secure |
| BLAKE3 | 256 (configurable) | 64 chars | Much faster | Secure |
SHA-256 and SHA-512 are both part of the SHA-2 family. On modern 64-bit processors, SHA-512 is actually faster than SHA-256 because it uses 64-bit arithmetic natively.
## How SHA-256 Works (Simplified)
1. **Padding.** The input message is padded so its length in bits is congruent to 448 modulo 512. A `1` bit is appended, then zeros, then the original message length as a 64-bit integer.
2. **Block processing.** The padded message is split into 512-bit (64-byte) blocks.
3. **Compression rounds.** Each block runs through 64 rounds of mixing using bitwise operations, modular addition, and constants derived from the cube roots of the first 64 primes.
4. **Output.** The final internal state (eight 32-bit words) is concatenated to produce the 256-bit hash.
The key properties this achieves:
- **Deterministic.** Same input always produces the same hash.
- **Avalanche effect.** Changing a single bit in the input changes roughly 50% of the output bits.
- **One-way.** You cannot recover the input from the hash.
- **Collision resistant.** Finding two different inputs that produce the same hash is computationally infeasible. The probability of a random collision is $1$ in $2^{256}$, which is approximately $1.16 \times 10^{77}$.
## Real-World Applications
### File integrity verification
```bash
# Generate checksum
sha256sum myfile.tar.gz > myfile.sha256
# Verify on another machine
sha256sum -c myfile.sha256
# myfile.tar.gz: OK
```
### Password hashing (do not use SHA-256 alone)
SHA-256 is too fast for password hashing. Use a purpose-built algorithm instead:
```python
# BAD: SHA-256 for passwords (vulnerable to brute force)
hashlib.sha256(password.encode()).hexdigest()
# GOOD: Use bcrypt, scrypt, or argon2
import bcrypt
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
```
### Digital signatures and certificates
TLS certificates use SHA-256 to create a fingerprint of the certificate content. The signature covers this hash, not the raw certificate.
### Blockchain (Bitcoin)
Bitcoin uses double SHA-256: `SHA256(SHA256(block_header))`. The mining process searches for a nonce that makes this hash start with a specific number of zero bits.
### Git commit hashes
Git uses SHA-1 by default (40 hex characters), but is migrating to SHA-256 (64 hex characters) for stronger collision resistance.
### API request signing (AWS Signature V4)
AWS uses SHA-256 to hash the request payload as part of its signing process:
```python
import hashlib, hmac
payload_hash = hashlib.sha256(request_body.encode()).hexdigest()
string_to_sign = f"AWS4-HMAC-SHA256\n{timestamp}\n{scope}\n{payload_hash}"
```
## Database Storage Considerations
When storing SHA-256 hashes in a database:
| Storage format | Column type | Size | Indexable |
|---------------|-------------|------|-----------|
| Hex string | `CHAR(64)` | 64 bytes | Yes |
| Binary | `BINARY(32)` | 32 bytes | Yes |
| Base64 | `CHAR(44)` | 44 bytes | Yes |
Using `BINARY(32)` saves 50% storage compared to `CHAR(64)` and is slightly faster for comparisons. Use `CHAR(64)` when human readability matters (logs, APIs, debugging).
```sql
-- MySQL example
CREATE TABLE file_checksums (
id INT PRIMARY KEY AUTO_INCREMENT,
filename VARCHAR(255) NOT NULL,
sha256_hash BINARY(32) NOT NULL,
INDEX idx_hash (sha256_hash)
);
-- Insert (converting hex to binary)
INSERT INTO file_checksums (filename, sha256_hash)
VALUES ('report.pdf', UNHEX('dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f'));
-- Query (converting back to hex for display)
SELECT filename, HEX(sha256_hash) FROM file_checksums;
```
## Common Pitfalls
- **Confusing hex length with byte length.** The hash is 32 bytes. The hex string representation is 64 characters. If your database column is `CHAR(32)`, it will truncate the hex string.
- **Using SHA-256 for passwords.** SHA-256 is designed to be fast. Use bcrypt, scrypt, or argon2 for password hashing instead.
- **Newline sensitivity.** `echo "test" | sha256sum` and `echo -n "test" | sha256sum` produce different hashes because `echo` appends a newline by default. Always use `-n` for consistent results.
- **Encoding matters.** "Hello" in UTF-8 and "Hello" in UTF-16 produce different hashes because the byte representations differ.
- **SHA-256 is not encryption.** Hashing is one-way. You cannot "decrypt" a hash to get the original input. If you need reversibility, use encryption (AES, ChaCha20).
- **Case sensitivity in hex.** `ABCD` and `abcd` represent the same hash value. Normalize to lowercase before comparing.
## Summary
- SHA-256 always produces a **256-bit (32-byte, 64 hex character)** output, regardless of input size.
- It is part of the SHA-2 family, published by NIST, and remains cryptographically secure with no known practical attacks.
- Use it for file integrity checks, digital signatures, blockchain, and data deduplication.
- Do not use it alone for password hashing. Use bcrypt, scrypt, or argon2 instead.
- Store as `BINARY(32)` in databases for space efficiency, or `CHAR(64)` for readability.
- The hex representation is always lowercase or uppercase 64 characters. Normalize case before comparing.
Related reading
- How not hybrid p2p programs know about others peers?
- How secure are Amazon AWS Access keys?
- How serious is this new ASP.NET security vulnerability and how can I workaround it?
- How set up Spring Boot to run HTTPS / HTTP ports
- How many additional function calls does fibn require if LINE 3 is removed?
- how many consecutive elements are smaller before each item in the array
- How should I resolve --secure-file-priv in MySQL?
- How to access RabbitMq publicly

Course
Beginner
27 lessons
10 hours
System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.