Generate a SHA-256 hash of a string. SHA-256 produces a fixed 64-character hexadecimal output regardless of input size.
Code
Utilitiesconst encoder = new TextEncoder();
const data = encoder.encode(str);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(hashBuffer)).map(b => b.toString(16).padStart(2, '0')).join('');Parameters
String to hash.
What is SHA-256?
SHA-256 (Secure Hash Algorithm 256-bit) is a cryptographic hash function that:
- Takes any input and produces a fixed 256-bit (64 hex character) output
- Is one-way — you cannot reverse a hash to get the original input
- Is deterministic — same input always produces same output
- Has avalanche effect — tiny input change completely changes the hash
"hello" → "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
"hello!" → "ce06092fb948d9ffac7d1a376e404b26b7575bcc11ee05a4615fef4fec3a308b"
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Completely different despite only adding "!"
When to Use Hashing
| Use Case | Example |
|---|---|
| Data integrity | Verify file downloads haven't been corrupted |
| Checksums | Detect duplicate files by comparing hashes |
| Caching keys | Generate cache keys from request parameters |
| Commit IDs | Git uses SHA for commit identifiers |
When NOT to Use Plain SHA-256
For passwords — use bcrypt, scrypt, or Argon2
Plain SHA-256 is too fast! Attackers can try billions of guesses per second. Password hashing algorithms are intentionally slow.
// BAD: SHA-256 for passwords
sha256("password123")
// GOOD: Use a password hashing library
bcrypt.hash("password123", saltRounds)
For secrets — add a salt
Without a salt, identical inputs produce identical hashes, making rainbow table attacks possible.
// BAD: Predictable hash
sha256(email)
// GOOD: Add random salt
sha256(email + randomSalt)
Hashing vs Encryption
| Hashing | Encryption |
|---|---|
| One-way (irreversible) | Two-way (reversible with key) |
| Fixed output size | Output size varies with input |
| For verification | For confidentiality |
| No key needed | Requires encryption key |
More JavaScript Snippets
Constant Time Compare
Compare two strings in constant time to prevent timing attacks. Unlike === which returns early on first mismatch, this compares all characters regardless of where differences occur.
FNV-1a Hash
Fast non-cryptographic hash function.
Generate Password
Generate a cryptographically secure random password with configurable options.
Parse JWT Payload
Extract and decode the payload from a JWT token without verification. Useful for reading claims like user ID, expiration time, and roles from tokens.
Simple String Hash
Generate a simple numeric hash from a string.
XSS Attack Prevention
Escape HTML entities to prevent Cross-Site Scripting attacks.