#= Security

Hash Function Code Examples — MD5, SHA256, bcrypt

Copy-paste hashing examples: MD5, SHA-1, SHA-256, SHA-512, bcrypt, and HMAC. Ready-to-use code for JavaScript, Python, PHP, Go, Java, and Rust.

SHA-256 Hash in JavaScript (Browser)

javascript

Use the Web Crypto API for SHA-256 hashing in the browser.

// Browser (Web Crypto API)
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('');
}

// Usage
sha256('Hello, World!').then(hash => {
  console.log(hash);
  // "dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"
});

MD5, SHA-256, SHA-512 in Node.js

javascript

Use the built-in crypto module for hashing in Node.js.

const crypto = require('crypto');

// MD5
const md5 = crypto.createHash('md5')
  .update('Hello, World!')
  .digest('hex');
console.log('MD5:', md5);
// "65a8e27d8879283831b664bd8b7f0ad4"

// SHA-256
const sha256 = crypto.createHash('sha256')
  .update('Hello, World!')
  .digest('hex');
console.log('SHA-256:', sha256);

// SHA-512
const sha512 = crypto.createHash('sha512')
  .update('Hello, World!')
  .digest('hex');
console.log('SHA-512:', sha512);

MD5, SHA-256, SHA-512 in Python

python

Use hashlib from the standard library for all common hash functions.

import hashlib

text = "Hello, World!"

# MD5
md5 = hashlib.md5(text.encode()).hexdigest()
print(f"MD5:    {md5}")
# "65a8e27d8879283831b664bd8b7f0ad4"

# SHA-256
sha256 = hashlib.sha256(text.encode()).hexdigest()
print(f"SHA-256: {sha256}")

# SHA-512
sha512 = hashlib.sha512(text.encode()).hexdigest()
print(f"SHA-512: {sha512}")

# Hash a file
with open("file.txt", "rb") as f:
    file_hash = hashlib.sha256(f.read()).hexdigest()
    print(f"File:   {file_hash}")

HMAC (Hash-Based Message Authentication) in Python

python

Create and verify HMAC signatures for API authentication.

import hmac
import hashlib

secret = b'my-secret-key'
message = b'data to authenticate'

# Create HMAC-SHA256 signature
signature = hmac.new(secret, message, hashlib.sha256).hexdigest()
print(signature)

# Verify a signature (constant-time comparison)
expected = signature
received = 'some-received-signature'
is_valid = hmac.compare_digest(expected, received)
print(f"Valid: {is_valid}")

bcrypt Password Hashing in Python

python

Use bcrypt for secure password storage (pip install bcrypt).

# pip install bcrypt
import bcrypt

password = b"my-secure-password"

# Hash a password (automatically generates salt)
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
print(hashed)
# b'$2b$12$LJ3m4ys3Lz...'

# Verify a password
is_correct = bcrypt.checkpw(password, hashed)
print(f"Password correct: {is_correct}")  # True

wrong = bcrypt.checkpw(b"wrong-password", hashed)
print(f"Wrong password: {wrong}")  # False

# Adjust cost factor (higher = slower but more secure)
hashed_slow = bcrypt.hashpw(password, bcrypt.gensalt(rounds=14))

MD5, SHA-256 & Password Hashing in PHP

php

PHP hash functions and password_hash() for secure password storage.

<?php
$text = "Hello, World!";

// MD5
echo md5($text); // "65a8e27d8879283831b664bd8b7f0ad4"

// SHA-256
echo hash('sha256', $text);

// HMAC
echo hash_hmac('sha256', $text, 'secret-key');

// Password hashing (recommended for passwords)
$password = "my-secure-password";
$hash = password_hash($password, PASSWORD_BCRYPT);

// Verify
if (password_verify($password, $hash)) {
    echo "Password is correct!";
}

// Hash a file
echo hash_file('sha256', 'file.txt');

MD5, SHA-256 & HMAC in Go

go

Use crypto packages for hashing in Go.

package main

import (
    "crypto/hmac"
    "crypto/md5"
    "crypto/sha256"
    "fmt"
)

func main() {
    data := []byte("Hello, World!")

    // MD5
    md5Hash := md5.Sum(data)
    fmt.Printf("MD5:    %x\n", md5Hash)

    // SHA-256
    sha256Hash := sha256.Sum256(data)
    fmt.Printf("SHA-256: %x\n", sha256Hash)

    // HMAC-SHA256
    secret := []byte("my-secret-key")
    mac := hmac.New(sha256.New, secret)
    mac.Write(data)
    signature := mac.Sum(nil)
    fmt.Printf("HMAC:   %x\n", signature)
}

bcrypt Password Hashing in Go

go

Use golang.org/x/crypto/bcrypt for password hashing.

package main

import (
    "fmt"
    "golang.org/x/crypto/bcrypt"
)

func main() {
    password := []byte("my-secure-password")

    // Hash password
    hash, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
    if err != nil {
        panic(err)
    }
    fmt.Println("Hash:", string(hash))

    // Verify password
    err = bcrypt.CompareHashAndPassword(hash, password)
    if err == nil {
        fmt.Println("Password correct!")
    }
}

MD5, SHA-256 & HMAC in Java

java

Use MessageDigest and Mac classes for hashing.

import java.security.MessageDigest;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HashExample {
    public static void main(String[] args) throws Exception {
        String text = "Hello, World!";

        // SHA-256
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hash = md.digest(text.getBytes("UTF-8"));
        StringBuilder hex = new StringBuilder();
        for (byte b : hash) {
            hex.append(String.format("%02x", b));
        }
        System.out.println("SHA-256: " + hex);

        // HMAC-SHA256
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec key = new SecretKeySpec(
            "secret".getBytes(), "HmacSHA256"
        );
        mac.init(key);
        byte[] hmac = mac.doFinal(text.getBytes("UTF-8"));
    }
}

SHA-256 & MD5 in Rust

rust

Use the sha2 and md-5 crates for hashing.

// Cargo.toml:
// sha2 = "0.10"
// md-5 = "0.10"

use md5;
use sha2::{Sha256, Digest};

fn main() {
    let data = b"Hello, World!";

    // MD5
    let md5_hash = md5::compute(data);
    println!("MD5:    {:x}", md5_hash);

    // SHA-256
    let mut hasher = Sha256::new();
    hasher.update(data);
    let sha256_hash = hasher.finalize();
    println!("SHA-256: {:x}", sha256_hash);
}

SHA-256, MD5 & HMAC in C#

csharp

Use System.Security.Cryptography for hashing in .NET.

using System.Security.Cryptography;
using System.Text;

string text = "Hello, World!";
byte[] data = Encoding.UTF8.GetBytes(text);

// SHA-256
byte[] sha256 = SHA256.HashData(data);
Console.WriteLine("SHA-256: " + Convert.ToHexString(sha256).ToLower());

// MD5
byte[] md5 = MD5.HashData(data);
Console.WriteLine("MD5: " + Convert.ToHexString(md5).ToLower());

// HMAC-SHA256
byte[] key = Encoding.UTF8.GetBytes("secret-key");
byte[] hmac = HMACSHA256.HashData(key, data);
Console.WriteLine("HMAC: " + Convert.ToHexString(hmac).ToLower());

MD5, SHA-256 & bcrypt in Ruby

ruby

Use Digest module and bcrypt gem for hashing in Ruby.

require 'digest'
require 'openssl'

text = 'Hello, World!'

# MD5
puts "MD5:    " + Digest::MD5.hexdigest(text)

# SHA-256
puts "SHA-256: " + Digest::SHA256.hexdigest(text)

# HMAC-SHA256
hmac = OpenSSL::HMAC.hexdigest('SHA256', 'secret-key', text)
puts "HMAC:   " + hmac

# bcrypt (gem install bcrypt)
require 'bcrypt'
hash = BCrypt::Password.create('my-password')
puts hash  # "$2a$12$..."
puts BCrypt::Password.new(hash) == 'my-password'  # true

Hash Functions in Bash (CLI)

bash

Use command-line tools for hashing on Linux/macOS.

# MD5
echo -n "Hello, World!" | md5sum    # Linux
echo -n "Hello, World!" | md5       # macOS

# SHA-256
echo -n "Hello, World!" | sha256sum    # Linux
echo -n "Hello, World!" | shasum -a 256  # macOS

# Hash a file
sha256sum file.txt
md5sum file.txt

# Verify file integrity
sha256sum --check checksums.txt

# HMAC (using openssl)
echo -n "Hello, World!" | openssl dgst -sha256 -hmac "secret-key"

Hash Algorithm Comparison Table

text

Quick reference comparing hash algorithms by output size and use case.

Algorithm   Output Size   Speed     Use Case
---------   -----------   -----     --------
MD5         128 bits      Fast      Checksums (NOT security)
SHA-1       160 bits      Fast      Legacy (deprecated for security)
SHA-256     256 bits      Medium    Digital signatures, blockchain
SHA-512     512 bits      Medium    High-security applications
bcrypt      184 bits      Slow*     Password storage
Argon2      Variable      Slow*     Password storage (modern)
HMAC        Varies        Medium    API authentication, webhooks

* Intentionally slow - resistant to brute force attacks.

IMPORTANT: Never use MD5 or SHA-1 for passwords or security.
Use bcrypt or Argon2 for password hashing.
Use SHA-256+ for integrity verification and signatures.

Need to work with hash functions right now?

Use our free online hash generator — no signup, no install, works in your browser.

Open Hash Generator →

More Code Snippets