Skip to main content

MD5 Hashing in JavaScript: Libraries and Methods

Learn MD5 hashing in JavaScript with CryptoJS and Node.js crypto module. Code examples, browser usage, and why to prefer SHA-256 for security.

How to Generate MD5 Hashes in JavaScript

JavaScript does not include a native MD5 function. The Web Crypto API supports SHA-1, SHA-256, SHA-384, and SHA-512, but deliberately excludes MD5 because it is cryptographically broken. For non-security use cases like checksums, cache keys, or content fingerprinting, you can use the CryptoJS library in the browser or the built-in crypto module in Node.js.

Browser: Using CryptoJS

<script src=\"https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.2.0/crypto-js.min.js\"></script>
<script>
// Generate MD5 hash
const hash = CryptoJS.MD5(\"Hello, World!\").toString();
console.log(hash); // \"65a8e27d8879283831b664bd8b7f0ad4\"

// Hash with hex encoding (default)
const hexHash = CryptoJS.MD5(\"test\").toString(CryptoJS.enc.Hex);

// Hash with Base64 encoding
const b64Hash = CryptoJS.MD5(\"test\").toString(CryptoJS.enc.Base64);
</script>

Node.js: Built-in crypto Module

const crypto = require(\"crypto\");

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

// Hash a file (streaming, memory-efficient)
const fs = require(\"fs\");
const fileHash = crypto.createHash(\"md5\");
fs.createReadStream(\"large-file.zip\")
    .pipe(fileHash)
    .on(\"finish\", () => {
        console.log(\"File MD5:\", fileHash.digest(\"hex\"));
    });

Why the Web Crypto API Excludes MD5

The Web Crypto API was designed with security in mind and only includes algorithms considered safe for cryptographic use. MD5 has known collision vulnerabilities since 2004, meaning two different inputs can produce the same hash. For integrity verification, use crypto.subtle.digest(\"SHA-256\", data) instead:

// Web Crypto API — SHA-256 (recommended alternative)
async function sha256(message) {
    const encoder = new TextEncoder();
    const data = encoder.encode(message);
    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(\"\");
}

Valid Use Cases for MD5 in JavaScript

  • Cache busting — generating short content hashes for URL query strings
  • Content deduplication — quickly comparing files by hash in non-adversarial contexts
  • Gravatar URLs — Gravatar uses MD5 hashes of email addresses for avatar URLs
  • Legacy API compatibility — some older APIs still require MD5 signatures

Try MD5 Generator Free

Generate MD5 hash from any text.

Use MD5 Generator →