DevGizmo
Back to Blog
cryptography·

How to Generate MD5, SHA-1, SHA-256 and SHA-512 Hashes in Python, JavaScript, PHP, Java and Go

Code examples for generating MD5, SHA-1, SHA-256 and SHA-512 cryptographic hashes in Python, JavaScript, Node.js, PHP, Java and Go. Copy-paste ready snippets for every language.

sha256sha512md5hashingpythonjavascriptcryptography

Cryptographic hash functions produce a fixed-length fingerprint from any input. This post is a practical code reference — copy the snippet for your language and go. For a deeper explanation of how hash functions work and when to use each algorithm, see SHA-256 and SHA-512 Hashing Explained.

Quick note on MD5 and SHA-1: both are cryptographically broken and must not be used for security-sensitive purposes (passwords, signatures, certificates). They are still commonly used for non-security checksums and legacy compatibility.


Python

Python's built-in hashlib module covers all four algorithms with a consistent API.

import hashlib

data = "Hello, World!"
encoded = data.encode("utf-8")

md5    = hashlib.md5(encoded).hexdigest()
sha1   = hashlib.sha1(encoded).hexdigest()
sha256 = hashlib.sha256(encoded).hexdigest()
sha512 = hashlib.sha512(encoded).hexdigest()

print(f"MD5:    {md5}")
print(f"SHA-1:  {sha1}")
print(f"SHA-256:{sha256}")
print(f"SHA-512:{sha512}")

Hashing a file in Python

import hashlib

def sha256_file(path: str) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()

print(sha256_file("document.pdf"))

Reading in chunks avoids loading the entire file into memory.


JavaScript (Browser)

The Web Crypto API is available in all modern browsers — no library needed.

async function hash(algorithm, message) {
  const data = new TextEncoder().encode(message);
  const buffer = await crypto.subtle.digest(algorithm, data);
  return Array.from(new Uint8Array(buffer))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
}

// algorithm must be "SHA-1", "SHA-256", or "SHA-512"
// Note: MD5 is not supported by the Web Crypto API
const digest = await hash("SHA-256", "Hello, World!");
console.log(digest);
// "dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986d"

The Web Crypto API does not support MD5. Use Node.js or a library like js-md5 if you need MD5 in the browser.


Node.js

Node.js exposes the native crypto module — no external dependencies.

const { createHash } = require("crypto");

const data = "Hello, World!";

const md5    = createHash("md5").update(data).digest("hex");
const sha1   = createHash("sha1").update(data).digest("hex");
const sha256 = createHash("sha256").update(data).digest("hex");
const sha512 = createHash("sha512").update(data).digest("hex");

console.log("MD5:    ", md5);
console.log("SHA-1:  ", sha1);
console.log("SHA-256:", sha256);
console.log("SHA-512:", sha512);

TypeScript

import { createHash } from "crypto";

function hashString(algorithm: string, input: string): string {
  return createHash(algorithm).update(input, "utf8").digest("hex");
}

const sha256 = hashString("sha256", "Hello, World!");

Hashing a file in Node.js

const { createHash } = require("crypto");
const { createReadStream } = require("fs");

function sha256File(path) {
  return new Promise((resolve, reject) => {
    const hash = createHash("sha256");
    createReadStream(path)
      .on("data", (chunk) => hash.update(chunk))
      .on("end", () => resolve(hash.digest("hex")))
      .on("error", reject);
  });
}

sha256File("document.pdf").then(console.log);

PHP

PHP provides hash() and hash_file() as built-in functions.

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

$md5    = hash("md5",    $data);
$sha1   = hash("sha1",   $data);
$sha256 = hash("sha256", $data);
$sha512 = hash("sha512", $data);

echo "MD5:    $md5\n";
echo "SHA-1:  $sha1\n";
echo "SHA-256:$sha256\n";
echo "SHA-512:$sha512\n";

Hashing a file in PHP

<?php
$sha256 = hash_file("sha256", "document.pdf");
echo $sha256;

Java

Java uses MessageDigest from java.security.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;

public class HashExample {
    public static String hash(String algorithm, String input)
            throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static void main(String[] args) throws Exception {
        String data = "Hello, World!";
        System.out.println("MD5:    " + hash("MD5",     data));
        System.out.println("SHA-1:  " + hash("SHA-1",   data));
        System.out.println("SHA-256:" + hash("SHA-256", data));
        System.out.println("SHA-512:" + hash("SHA-512", data));
    }
}

Common algorithm strings for MessageDigest.getInstance(): "MD5", "SHA-1", "SHA-256", "SHA-512".


Go

Go's standard library includes MD5, SHA-1, SHA-256, and SHA-512 in the crypto package.

package main

import (
    "crypto/md5"
    "crypto/sha1"
    "crypto/sha256"
    "crypto/sha512"
    "fmt"
)

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

    fmt.Printf("MD5:    %x\n", md5.Sum(data))
    fmt.Printf("SHA-1:  %x\n", sha1.Sum(data))
    fmt.Printf("SHA-256:%x\n", sha256.Sum256(data))
    fmt.Printf("SHA-512:%x\n", sha512.Sum512(data))
}

Hashing a file in Go

package main

import (
    "crypto/sha256"
    "fmt"
    "io"
    "os"
)

func sha256File(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 fmt.Sprintf("%x", h.Sum(nil)), nil
}

func main() {
    digest, _ := sha256File("document.pdf")
    fmt.Println(digest)
}

Expected Output for "Hello, World!"

AlgorithmHash
MD565a8e27d8879283831b664bd8b7f0ad4
SHA-10a0a9f2a6772942557ab5355d76af442f8f65e01
SHA-256dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986d
SHA-512374d794a95cdcfd8b35993185fef9ba368f160d8daf432d08ba9f1ed1e5abe6cc69291e0fa2fe0006a52570ef18c19def4e617c33ce52ef0a6e5fbe318cb0387

Use these to verify your implementation is working correctly.


Which Algorithm Should You Use?

Use caseRecommended algorithm
Password hashingbcrypt / Argon2 (not SHA)
File integrity check (non-security)MD5 or SHA-256
File integrity check (security-critical)SHA-256 or SHA-512
Digital signatures / certificatesSHA-256 or SHA-512
API request signing (HMAC)HMAC-SHA256
Legacy systemsMD5 / SHA-1 (check requirements)

Generate hashes directly in your browser with the SHA Hash Generator — no installation required.

Try it yourself

Put these concepts into practice with the free online tool on DevGizmo.