DevToolBoxGRATIS
Blogg

Hash Generator Online — MD5, SHA-256, SHA-512: The Complete Developer Guide

15 min readby DevToolBox

TL;DR

A hash generator converts any input into a fixed-size cryptographic fingerprint. Use SHA-256 for security-critical applications (file verification, digital signatures, blockchain). Use bcrypt or Argon2 for password hashing — never plain SHA-256 or MD5. Use HMAC-SHA256 for API authentication and webhook verification. MD5 is broken for security but acceptable for non-adversarial checksums. Try our free online hash generator for instant results, or follow the code examples below for JavaScript, Python, Go, and Rust.

What Is a Hash Function? Core Properties Explained

A hash function is a mathematical algorithm that accepts an input of arbitrary size and produces a fixed-size output called a hash digest. The output is typically represented as a hexadecimal string. For example, SHA-256(“hello”) always equals 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824, regardless of when or where you compute it.

Hash functions have five critical properties that make them essential across modern computing:

  • Deterministic: The same input always yields the same output.
  • Fixed-length output: Regardless of input size, the output is always the same length (e.g., 64 hex chars for SHA-256).
  • One-way (preimage resistant): Given a hash, it is computationally infeasible to recover the original input.
  • Avalanche effect: Changing even a single bit in the input drastically alters the output.
  • Collision resistant: Computationally infeasible to find two different inputs producing the same hash.

Algorithm Comparison Table

AlgorithmOutput BitsSpeedSecurity StatusPrimary Use Case
MD5128Very FastBroken (2004)Legacy checksums, cache keys, ETags
SHA-1160FastBroken (2017)Git (legacy), TOTP, fingerprints
SHA-256256ModerateSecureDigital signatures, blockchain, TLS, file verification
SHA-512512Fast on 64-bitSecureHigh-security apps, Ed25519 signatures
SHA-3224–512ModerateSecure (sponge)SHA-2 fallback, Ethereum (Keccak)
BLAKE3256 (default)Extremely FastSecureBuild tools, content addressing, high-throughput

MD5 and SHA-1 are broken for security purposes but remain acceptable for non-adversarial checksums, cache keys, and legacy compatibility. SHA-256 is the recommended default for all new security-critical applications.

JavaScript — Web Crypto API (Browser and Node.js 18+)

The Web Crypto API is available natively in all modern browsers and in Node.js 18+ via the global crypto.subtle object. It supports SHA-1, SHA-256, SHA-384, and SHA-512 (not MD5). Use TextEncoder to convert strings to bytes before hashing.

// Web Crypto API — works in browsers and Node.js 18+
async function sha256(text: string): Promise<string> {
  const encoder = new TextEncoder();
  const data = encoder.encode(text);
  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('');
}

// Usage
const hash = await sha256('hello');
// => "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

// SHA-512 — same pattern, different algorithm string
async function sha512(text: string): Promise<string> {
  const encoder = new TextEncoder();
  const data = encoder.encode(text);
  const hashBuffer = await crypto.subtle.digest('SHA-512', data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

// Supported algorithms: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512'
// Note: MD5 is NOT supported by Web Crypto API (use Node.js crypto module)

The Web Crypto API is asynchronous by design (returning Promises). The TextEncoder converts a UTF-8 string into a Uint8Array, which is what crypto.subtle.digest expects. The hex conversion maps each byte to a two-character hex string with leading zero padding.

JavaScript — Node.js crypto Module

The built-in crypto module in Node.js provides synchronous and streaming hash generation. It supports MD5, SHA-1, SHA-256, SHA-512, and many other algorithms via crypto.getHashes().

import crypto from 'crypto';
import { createReadStream } from 'fs';

// String hashing — synchronous
function hashString(input: string, algorithm = 'sha256'): string {
  return crypto.createHash(algorithm).update(input, 'utf8').digest('hex');
}

console.log(hashString('hello', 'md5'));
// => "5d41402abc4b2a76b9719d911017c592"

console.log(hashString('hello', 'sha256'));
// => "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

// Base64 output instead of hex
function hashBase64(input: string): string {
  return crypto.createHash('sha256').update(input).digest('base64');
}

// File hashing — streaming (memory-efficient for large files)
function hashFile(filePath: string, algorithm = 'sha256'): Promise<string> {
  return new Promise((resolve, reject) => {
    const hash = crypto.createHash(algorithm);
    const stream = createReadStream(filePath);
    stream.on('data', (chunk) => hash.update(chunk));
    stream.on('end', () => resolve(hash.digest('hex')));
    stream.on('error', reject);
  });
}

// Usage
const fileHash = await hashFile('./package.json', 'sha256');
console.log(`SHA-256: ${fileHash}`);

// List all supported algorithms
console.log(crypto.getHashes());
// [ 'md5', 'sha1', 'sha256', 'sha512', 'sha3-256', 'blake2b512', ... ]

HMAC — Message Authentication Code

HMAC (Hash-based Message Authentication Code) is a keyed-hash construction that verifies both the integrity and authenticity of a message. Unlike a plain hash which anyone can compute, HMAC requires knowledge of a secret key. Never use SHA-256(secret + message) — it is vulnerable to length extension attacks with Merkle-Damgard hash functions. HMAC prevents this by design.

import crypto from 'crypto';

// Node.js HMAC — used in API signing, webhooks, JWT
function hmacSha256(secret: string, message: string): string {
  return crypto.createHmac('sha256', secret).update(message).digest('hex');
}

const signature = hmacSha256('my-secret-key', 'payload data');
// => "a6b4f7c9d2e1..." (32-byte / 64-char hex)

// GitHub webhook verification example
function verifyGithubWebhook(secret: string, payload: string, signature: string): boolean {
  const expected = 'sha256=' + hmacSha256(secret, payload);
  return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}

// Web Crypto API HMAC (browser)
async function hmacSha256Browser(secret: string, message: string): Promise<string> {
  const encoder = new TextEncoder();
  const keyData = encoder.encode(secret);
  const key = await crypto.subtle.importKey(
    'raw', keyData, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
  );
  const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(message));
  return Array.from(new Uint8Array(signature))
    .map(b => b.toString(16).padStart(2, '0')).join('');
}

// When to use HMAC vs plain hash:
// - Plain hash: file integrity where no adversary can modify the file
// - HMAC: API authentication, webhooks, JWT signing, session tokens

Python — hashlib

Python's built-in hashlib module provides access to all major hash algorithms including MD5, SHA-1, SHA-256, SHA-512, SHA-3 variants, and BLAKE2. It also includes pbkdf2_hmac for key derivation.

import hashlib
import hmac
import os

# Basic string hashing — always encode to bytes first
text = "hello"

sha256_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
print(sha256_hash)
# => "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

md5_hash = hashlib.md5(text.encode()).hexdigest()
print(md5_hash)
# => "5d41402abc4b2a76b9719d911017c592"

# SHA-3 (different from SHA-2, sponge construction)
sha3_hash = hashlib.sha3_256(text.encode()).hexdigest()
print(sha3_hash)

# BLAKE2b — fast, secure, variable output
blake2b_hash = hashlib.blake2b(text.encode(), digest_size=32).hexdigest()

# File hashing with streaming (memory-efficient for large files)
def hash_file(filepath: str, algorithm: str = 'sha256') -> str:
    h = hashlib.new(algorithm)
    with open(filepath, 'rb') as f:
        while chunk := f.read(8192):
            h.update(chunk)
    return h.hexdigest()

file_hash = hash_file('/path/to/largefile.iso', 'sha256')
print(f"SHA-256: {file_hash}")

# PBKDF2 for key derivation (not for passwords — use bcrypt/argon2 instead)
password = b"my-password"
salt = os.urandom(16)
key = hashlib.pbkdf2_hmac('sha256', password, salt, iterations=600000)
# Use argon2-cffi for password hashing in production

# List all supported algorithms
print(hashlib.algorithms_guaranteed)
# {'sha256', 'sha512', 'sha3_256', 'blake2b', 'md5', ...}

Password Hashing — bcrypt and Argon2

SHA-256 is completely wrong for passwords. SHA-256 is designed to be fast — an attacker with a modern GPU can compute 10+ billion SHA-256 hashes per second, making brute-force attacks against password databases trivially easy. Proper password hashing uses intentionally slow, memory-hard algorithms.

# Python: bcrypt (install: pip install bcrypt)
import bcrypt

def hash_password(password: str) -> bytes:
    salt = bcrypt.gensalt(rounds=12)  # work factor 12 (~250ms on modern hardware)
    return bcrypt.hashpw(password.encode('utf-8'), salt)

def verify_password(password: str, hashed: bytes) -> bool:
    return bcrypt.checkpw(password.encode('utf-8'), hashed)

hashed = hash_password("correct-horse-battery-staple")
print(hashed)
# => b'$2b$12$...' (60-char bcrypt hash with embedded salt and cost)

is_valid = verify_password("correct-horse-battery-staple", hashed)
print(is_valid)  # => True

# Python: argon2-cffi (install: pip install argon2-cffi)
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher(
    time_cost=3,       # number of iterations
    memory_cost=65536, # 64 MB memory
    parallelism=4,     # threads
)

hashed_pw = ph.hash("my-password")
# => "$argon2id$v=19$m=65536,t=3,p=4$..."

try:
    ph.verify(hashed_pw, "my-password")  # raises on failure
    print("Valid!")
except VerifyMismatchError:
    print("Invalid password")
// Node.js: bcryptjs (pure JS, no native deps)
import bcrypt from 'bcryptjs';

async function hashPassword(password: string): Promise<string> {
  const saltRounds = 12; // work factor — increase every few years
  return bcrypt.hash(password, saltRounds);
}

async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return bcrypt.compare(password, hash);
}

const hash = await hashPassword('my-secure-password');
// => "$2a$12$..." (60-char bcrypt string)

const isValid = await verifyPassword('my-secure-password', hash);
// => true

// RULE: Never store plain passwords or MD5/SHA-256 password hashes
// RULE: The work factor should be tuned so hashing takes ~250-500ms
// RULE: bcrypt has a 72-byte input limit — use Argon2 for longer inputs

Go — crypto Package

Go's standard library provides crypto/sha256, crypto/sha512, crypto/sha1,crypto/md5, and crypto/hmac. Use fmt.Sprintf("%x", hash) for hex encoding.

package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "crypto/sha512"
    "encoding/hex"
    "fmt"
    "io"
    "os"
)

// SHA-256 of a string — one-shot
func hashStringSHA256(s string) string {
    h := sha256.Sum256([]byte(s))
    return fmt.Sprintf("%x", h)
}

// SHA-256 streaming — for large data
func hashStreamSHA256(r io.Reader) (string, error) {
    h := sha256.New()
    if _, err := io.Copy(h, r); err != nil {
        return "", err
    }
    return hex.EncodeToString(h.Sum(nil)), nil
}

// File integrity check
func hashFile(path string) (string, error) {
    f, err := os.Open(path)
    if err != nil {
        return "", err
    }
    defer f.Close()
    return hashStreamSHA256(f)
}

// HMAC-SHA256 for API signing
func hmacSHA256(key, message []byte) string {
    mac := hmac.New(sha256.New, key)
    mac.Write(message)
    return hex.EncodeToString(mac.Sum(nil))
}

func main() {
    fmt.Println(hashStringSHA256("hello"))
    // => 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

    // SHA-512
    h512 := sha512.Sum512([]byte("hello"))
    fmt.Printf("%x\n", h512)

    // HMAC
    sig := hmacSHA256([]byte("secret"), []byte("payload"))
    fmt.Println(sig)
}

File Integrity Checking — Command Line

Every major operating system provides command-line tools for computing file checksums. These are essential for verifying downloaded software, ISO images, and release artifacts.

# Linux — sha256sum (coreutils)
sha256sum file.txt
# => 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824  file.txt

# Verify against a published checksum file
sha256sum -c SHA256SUMS
# => ubuntu-24.04.iso: OK

# Compute multiple algorithms at once
sha1sum file.txt    # SHA-1 (160-bit)
md5sum file.txt     # MD5 (128-bit, not for security)

# macOS — shasum
shasum -a 256 file.txt           # SHA-256
shasum -a 512 file.txt           # SHA-512
shasum -a 256 -c SHA256SUMS      # verify

# Windows PowerShell
Get-FileHash file.txt -Algorithm SHA256
Get-FileHash file.txt -Algorithm MD5

# Windows Command Prompt (certutil)
certutil -hashfile file.txt SHA256
certutil -hashfile file.txt MD5

# Verify a download — compare these two values:
shasum -a 256 ubuntu-24.04.iso
# vs the value published at https://releases.ubuntu.com/24.04/SHA256SUMS

Content Addressing — Git, IPFS, Docker, Webpack

Content-addressable systems use hash digests as identifiers, making it impossible for content to be silently replaced without changing its address.

  • Git: Each commit, tree, and blob is identified by its SHA-1 hash (SHA-256 via git init --object-format=sha256 in newer versions). The commit hash is the SHA-1 of the commit content plus parent hashes, making the entire history tamper-evident.
  • IPFS: Files are addressed by CID (Content Identifier) based on multihash (typically SHA-256 or SHA3-256). The same content always resolves to the same CID globally, enabling deduplication across nodes.
  • Docker: Image layers are identified by their SHA-256 digest (e.g., sha256:abc123def456...). The same layer can be shared between images, saving storage and bandwidth.
  • Webpack / build tools: The [contenthash] placeholder generates a short hash of file content for cache-busting filenames (e.g., main.a3f7b2.js). Browsers cache files indefinitely, and the hash changes only when content changes.
# Git — view the hash of a commit or file
git log --oneline -5
# a3f7b2c Fix authentication bug
# 8e1d9f2 Add password hashing

git cat-file -t a3f7b2c    # => commit
git cat-file -p a3f7b2c    # => show commit content

# Docker — pull by digest (pinned, immutable)
docker pull nginx@sha256:abc123def456...
docker inspect nginx:latest | jq '.[0].RepoDigests'

# Webpack config — content hashing for cache busting
// webpack.config.js
module.exports = {
  output: {
    filename: '[name].[contenthash:8].js',
    chunkFilename: '[name].[contenthash:8].chunk.js',
  }
};
// => main.a3f7b2c8.js (8-char truncated SHA-256)

Hash Collisions and Security — What You Need to Know

A collision occurs when two different inputs produce the same hash output. Collision resistance is a fundamental security requirement for hash functions used in digital signatures, certificates, and code signing.

  • MD5 (2004): Xiaoyun Wang demonstrated practical collision attacks. By 2008, MD5 collisions were used to forge a rogue Certificate Authority certificate. In 2012, the Flame malware exploited MD5 weaknesses in Windows Update. MD5 collisions can now be generated in under a second on commodity hardware.
  • SHA-1 SHAttered (2017): Google and CWI Amsterdam published the first practical SHA-1 collision, creating two different PDF files with the same SHA-1 hash. The attack cost approximately $110,000 in cloud computing. Major browsers deprecated SHA-1 certificates in 2017.
  • What “collision-resistant” means: SHA-256 provides 128-bit collision resistance, meaning an attacker needs ~2^128 operations to find a collision — far beyond the capability of all current and foreseeable computing resources. SHA-512 provides 256-bit resistance.
  • Why it matters: If an attacker can create a collision, they can craft a malicious document with the same hash as a legitimate one, bypassing digital signature verification. This has real consequences for code signing certificates, software distribution, and document authentication.

Recommended algorithms today: SHA-256 (widely supported, secure), SHA-512 (larger security margin), SHA-3 (sponge construction, no length extension attacks), BLAKE3 (fastest, excellent for high-throughput). Avoid MD5 and SHA-1 for any security purpose.

Rust — sha2 and blake3 Crates

Rust has excellent cryptographic library support via the sha2, blake3, and hmac crates from the RustCrypto project. BLAKE3 is particularly popular in Rust because the official blake3 crate is authored by the BLAKE3 designers.

# Cargo.toml
[dependencies]
sha2 = "0.10"
sha3 = "0.10"
blake3 = "1"
hmac = "0.12"
hex = "0.4"
digest = "0.10"
use sha2::{Sha256, Sha512, Digest};
use sha3::Sha3_256;
use hmac::{Hmac, Mac};
use sha2::Sha256 as HmacSha256;

fn main() {
    // SHA-256 one-shot
    let hash = Sha256::digest(b"hello");
    println!("{:x}", hash);
    // => 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

    // SHA-256 streaming (for large inputs)
    let mut hasher = Sha256::new();
    hasher.update(b"first chunk");
    hasher.update(b"second chunk");
    let result = hasher.finalize();
    println!("{:x}", result);

    // SHA-512
    let hash512 = Sha512::digest(b"hello");
    println!("{:x}", hash512);

    // SHA-3 (Keccak-based, sponge construction)
    let sha3 = Sha3_256::digest(b"hello");
    println!("{:x}", sha3);

    // BLAKE3 — extremely fast
    let b3 = blake3::hash(b"hello");
    println!("{}", b3.to_hex());

    // HMAC-SHA256
    type HmacSha256Type = Hmac<HmacSha256>;
    let mut mac = HmacSha256Type::new_from_slice(b"my-secret-key")
        .expect("HMAC accepts any key length");
    mac.update(b"payload data");
    let signature = mac.finalize().into_bytes();
    println!("{}", hex::encode(signature));
}

Practical Use Cases — Patterns Every Developer Should Know

API Request Signing

// API request signing — include signature in header
import crypto from 'crypto';

function signRequest(
  method: string,
  path: string,
  body: string,
  secret: string,
  timestamp: string
): string {
  const payload = `${method}\n${path}\n${timestamp}\n${body}`;
  return crypto.createHmac('sha256', secret).update(payload).digest('hex');
}

// Client sends:
const timestamp = Date.now().toString();
const signature = signRequest('POST', '/api/orders', '{"qty":1}', apiSecret, timestamp);
// Headers: { 'X-Timestamp': timestamp, 'X-Signature': signature }

// Server verifies:
function verifyRequest(receivedSig: string, ...args: Parameters<typeof signRequest>): boolean {
  const expected = signRequest(...args);
  return crypto.timingSafeEqual(Buffer.from(receivedSig), Buffer.from(expected));
  // Use timingSafeEqual to prevent timing attacks
}

Content Deduplication and Cache Keys

import crypto from 'crypto';

// Content deduplication — detect duplicates without full comparison
function contentKey(content: string | Buffer): string {
  return crypto.createHash('sha256').update(content).digest('hex');
}

const files = new Map<string, string>(); // hash -> filename
async function deduplicatedUpload(filename: string, content: Buffer) {
  const hash = contentKey(content);
  if (files.has(hash)) {
    console.log(`Duplicate detected: ${filename} = ${files.get(hash)}`);
    return; // skip upload
  }
  files.set(hash, filename);
  // await s3.upload(hash, content);
}

// Cache key generation — short MD5 for non-security use
function cacheKey(params: Record<string, unknown>): string {
  const normalized = JSON.stringify(params, Object.keys(params).sort());
  return crypto.createHash('md5').update(normalized).digest('hex').slice(0, 12);
  // e.g. "a3f7b2c8d1e4" (12-char is plenty for cache keys)
}

// File change detection — hash before and after
async function hasFileChanged(path: string, previousHash: string): Promise<boolean> {
  const current = await hashFile(path);
  return current !== previousHash;
}

URL-Safe IDs and Random Tokens

import crypto from 'crypto';

// Cryptographically secure random token (for password reset links, API keys)
function generateToken(bytes = 32): string {
  return crypto.randomBytes(bytes).toString('hex');
  // 32 bytes => 64-char hex token with 256 bits of entropy
}

// URL-safe base64 token
function generateUrlSafeToken(bytes = 32): string {
  return crypto.randomBytes(bytes).toString('base64url');
  // e.g. "xK7mZp2QrNvBwLfAeHqIuT..."
}

// Deterministic ID from content (content-addressable)
function contentId(data: string): string {
  return crypto.createHash('sha256').update(data).digest('hex').slice(0, 16);
  // 16-char hex (64 bits) — safe for millions of items
}

// UUID v4 is fine for most cases (not hash-based)
const uuid = crypto.randomUUID();
// => "550e8400-e29b-41d4-a716-446655440000"

Key Takeaways

  • SHA-256 is the industry-standard choice for general-purpose cryptographic hashing with no known practical attacks.
  • MD5 and SHA-1 are cryptographically broken — never use them for security, signatures, or certificates.
  • Use bcrypt or Argon2 (never SHA-256) for password hashing — they are intentionally slow and memory-hard.
  • Use HMAC-SHA256 (not plain SHA-256) for API request signing and webhook verification to prevent length extension attacks.
  • The Web Crypto API works natively in browsers and Node.js 18+ without any dependencies.
  • Python hashlib, Go crypto package, and Rust sha2 crate all provide high-quality hash implementations.
  • Content-addressable systems (Git, Docker, IPFS, Webpack) use SHA-256 digests as tamper-evident identifiers.
  • BLAKE3 is the fastest modern hash function — ideal for high-throughput use cases where SHA-256 is a bottleneck.
  • Use crypto.timingSafeEqual() when comparing HMAC signatures to prevent timing-based side-channel attacks.
𝕏 Twitterin LinkedIn
Var detta hjälpsamt?

Håll dig uppdaterad

Få veckovisa dev-tips och nya verktyg.

Ingen spam. Avsluta när som helst.

Try These Related Tools

#Hash Generator🔐HMAC Generator🔒Bcrypt Hash Generator

Related Articles

MD5 & SHA-256 Hash Generator: Komplett Guide med Kodexempel

Gratis online MD5 och SHA-256 hash generator. Lar dig hur hashfunktioner fungerar med kodexempel i JavaScript, Python och Bash.

bcrypt vs Argon2 vs scrypt: Lösenordshashing 2026

Jämför bcrypt, Argon2id och scrypt.

Lösenordsstyrka-krav 2025: NIST-riktlinjer & bästa praxis

Moderna lösenordskrav baserade på NIST SP 800-63B.