Hash code examples
Hashing "Hello, World!" in popular languages, plus an HMAC with the key "secret". Each one should print these (PowerShell in uppercase):
- SHA-256
- dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
- MD5
- 65a8e27d8879283831b664bd8b7f0ad4
- HMAC-SHA256
- fcfaffa7fef86515c7beb6b62d779fa4ccf092f2e61c164376054271252821ff
Hashing in JavaScript (browser)
The Web Crypto API offers SHA-1, SHA-256, SHA-384 and SHA-512, but not MD5 or SHA-3. For those, use a library such as @noble/hashes.
const toHex = (buf) =>
Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join("");
const enc = new TextEncoder();
// SHA-256
const digest = await crypto.subtle.digest("SHA-256", enc.encode("Hello, World!"));
console.log("SHA-256:", toHex(digest));
// HMAC-SHA256
const key = await crypto.subtle.importKey(
"raw", enc.encode("secret"), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]
);
const mac = await crypto.subtle.sign("HMAC", key, enc.encode("Hello, World!"));
console.log("HMAC-SHA256:", toHex(mac));Hashing in Node.js
import { createHash, createHmac } from "node:crypto";
import { createReadStream } from "node:fs";
console.log("SHA-256:", createHash("sha256").update("Hello, World!").digest("hex"));
console.log("MD5:", createHash("md5").update("Hello, World!").digest("hex"));
console.log("HMAC-SHA256:", createHmac("sha256", "secret").update("Hello, World!").digest("hex"));
// A file, streamed so it never has to fit in memory
async function hashFile(path, algorithm = "sha256") {
const hash = createHash(algorithm);
for await (const chunk of createReadStream(path)) hash.update(chunk);
return hash.digest("hex");
}
// console.log(await hashFile("download.iso"));Hashing in Python
import hashlib
import hmac
data = "Hello, World!".encode("utf-8")
print("SHA-256:", hashlib.sha256(data).hexdigest())
print("MD5:", hashlib.md5(data).hexdigest())
print("HMAC-SHA256:", hmac.new(b"secret", data, hashlib.sha256).hexdigest())
# A file (Python 3.11+), read in chunks
def hash_file(path, algorithm="sha256"):
with open(path, "rb") as f:
return hashlib.file_digest(f, algorithm).hexdigest()
# Also built in: sha3_256, blake2b, blake2s, sha512 ...Hashing in Java
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class Main {
public static void main(String[] args) throws Exception {
byte[] data = "Hello, World!".getBytes(StandardCharsets.UTF_8);
HexFormat hex = HexFormat.of(); // Java 17+
System.out.println("SHA-256: " + hex.formatHex(MessageDigest.getInstance("SHA-256").digest(data)));
System.out.println("MD5: " + hex.formatHex(MessageDigest.getInstance("MD5").digest(data)));
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec("secret".getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
System.out.println("HMAC-SHA256: " + hex.formatHex(mac.doFinal(data)));
// Also available: "SHA-512", "SHA3-256", "SHA-1" ...
}
}Hashing in C# / .NET
Convert.ToHexStringLower needs .NET 9 or later. On older versions use Convert.ToHexString(...).ToLowerInvariant().
using System;
using System.Security.Cryptography;
using System.Text;
byte[] data = Encoding.UTF8.GetBytes("Hello, World!");
Console.WriteLine("SHA-256: " + Convert.ToHexStringLower(SHA256.HashData(data)));
Console.WriteLine("MD5: " + Convert.ToHexStringLower(MD5.HashData(data)));
Console.WriteLine("HMAC-SHA256: " +
Convert.ToHexStringLower(HMACSHA256.HashData(Encoding.UTF8.GetBytes("secret"), data)));
// A file
// using var stream = File.OpenRead("download.iso");
// string fileHash = Convert.ToHexStringLower(SHA256.HashData(stream));Hashing in Go
package main
import (
"crypto/hmac"
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
)
func main() {
data := []byte("Hello, World!")
sum := sha256.Sum256(data)
fmt.Println("SHA-256:", hex.EncodeToString(sum[:]))
m := md5.Sum(data)
fmt.Println("MD5:", hex.EncodeToString(m[:]))
mac := hmac.New(sha256.New, []byte("secret"))
mac.Write(data)
fmt.Println("HMAC-SHA256:", hex.EncodeToString(mac.Sum(nil)))
}
// hashFile streams a file through SHA-256.
func hashFile(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}Hashing in Rust
Install: cargo add sha2 md-5 hmac hex
use hmac::{Hmac, KeyInit, Mac};
use md5::Md5;
use sha2::{Digest, Sha256};
fn main() {
let data = b"Hello, World!";
println!("SHA-256: {}", hex::encode(Sha256::digest(data)));
println!("MD5: {}", hex::encode(Md5::digest(data)));
let mut mac = Hmac::<Sha256>::new_from_slice(b"secret").expect("any key length works");
mac.update(data);
println!("HMAC-SHA256: {}", hex::encode(mac.finalize().into_bytes()));
}Hashing in PHP
<?php
$data = "Hello, World!";
echo "SHA-256: " . hash("sha256", $data) . "\n";
echo "MD5: " . md5($data) . "\n";
echo "HMAC-SHA256: " . hash_hmac("sha256", $data, "secret") . "\n";
// A file: hash_file("sha256", "download.iso")
// Every algorithm PHP knows: print_r(hash_algos());Hashing in Bash / Linux
Use printf or echo -n: plain echo adds a newline, which changes the hash. On macOS use shasum -a 256 and md5.
printf '%s' 'Hello, World!' | sha256sum
printf '%s' 'Hello, World!' | md5sum
printf '%s' 'Hello, World!' | openssl dgst -sha256 -hmac 'secret'
# Files, and checking them later
sha256sum *.iso > checksums.sha256
sha256sum -c checksums.sha256Hashing in PowerShell
Get-FileHash works in Windows PowerShell 5.1 and PowerShell 7. It prints uppercase hex.
$bytes = [Text.Encoding]::UTF8.GetBytes("Hello, World!")
$stream = [IO.MemoryStream]::new($bytes)
(Get-FileHash -InputStream $stream -Algorithm SHA256).Hash
$stream.Position = 0
(Get-FileHash -InputStream $stream -Algorithm MD5).Hash
$hmac = [Security.Cryptography.HMACSHA256]::new([Text.Encoding]::UTF8.GetBytes("secret"))
[BitConverter]::ToString($hmac.ComputeHash($bytes)).Replace("-", "")
# A file
Get-FileHash .\download.iso -Algorithm SHA256