How do you generate a SHA-256 or MD5 hash from a string in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you generate a SHA-256 or MD5 hash from a string in JavaScript?

message-square
0

To generate a SHA-256 or MD5 hash from a string in JavaScript, use the runtime’s native cryptographic APIs rather than hand-rolling hash logic: in Node.js, use node:crypto (crypto.createHash("sha256") or crypto.createHash("md5")), and in modern browsers (or cross-runtime code), use the Web Crypto API (crypto.subtle.digest("SHA-256", bytes)) for SHA-256 (note that Web Crypto does not support MD5). Always use SHA-256 (or stronger algorithms like SHA-512 / HMAC-SHA256) for integrity checks, tokens, and digests—treat MD5 strictly as a non-cryptographic checksum (for example, legacy cache keys or non-security file fingerprints), never for passwords or security signatures.


1. Generating SHA-256 and MD5 Hashes in Node.js (node:crypto)

Use crypto.createHash(algorithm).update(input, "utf8").digest("hex") in Node.js to compute lowercase hexadecimal digests (or "base64" / "base64url" when compact encodings are needed):

// Generate SHA-256 or MD5 hex digests from a UTF-8 string in Node.js
import crypto from "node:crypto";

function hashStringNode(input, algorithm = "sha256", encoding = "hex") {
  if (typeof input !== "string") {
    throw new TypeError("Expected input to be a string.");
  }

  const normalizedAlgo = String(algorithm).toLowerCase();
  if (normalizedAlgo !== "sha256" && normalizedAlgo !== "md5") {
    throw new RangeError('Unsupported algorithm. Expected "sha256" or "md5".');
  }

  try {
    return crypto
      .createHash(normalizedAlgo)
      .update(input, "utf8")
      .digest(encoding);
  } catch (error) {
    throw new Error(`Failed to generate ${normalizedAlgo} digest: ${error.message}`);
  }
}

// Example usage:
try {
  const sha256Hex = hashStringNode("hello-world", "sha256");
  const md5Hex = hashStringNode("hello-world", "md5");
  console.log({ sha256Hex, md5Hex });
} catch (error) {
  console.error(`${error.name}: ${error.message}`);
}
  • Specify "utf8" explicitly: Ensures multi-byte Unicode characters (emoji, accented characters, scripts) hash deterministically across platforms.
  • Avoid MD5 for security or password hashing: MD5 suffers from collision attacks and lacks salting/work-factor cost; use dedicated password KDFs (scrypt, Argon2, bcrypt) for passwords and HMAC/SHA-256+ for verification.

2. Generating SHA-256 Hashes in Browsers with Web Crypto (crypto.subtle)

In browsers (and modern runtimes exposing crypto.subtle in a secure context such as https:// or localhost), encode the UTF-8 string with TextEncoder, digest with crypto.subtle.digest("SHA-256", data), and convert the resulting ArrayBuffer bytes into a lowercase hex string:

// Generate a lowercase SHA-256 hex digest using the Web Crypto API
async function hashSha256Browser(input) {
  if (typeof input !== "string") {
    throw new TypeError("Expected input to be a string.");
  }

  const subtle = globalThis.crypto?.subtle;
  if (!subtle || typeof subtle.digest !== "function") {
    throw new Error("Web Crypto subtle.digest is unavailable (requires a secure context).");
  }

  try {
    const encoder = new TextEncoder();
    const encodedBytes = encoder.encode(input);
    const digestBuffer = await subtle.digest("SHA-256", encodedBytes);
    const byteArray = new Uint8Array(digestBuffer);

    let hex = "";
    for (let i = 0; i < byteArray.length; i += 1) {
      hex += byteArray[i].toString(16).padStart(2, "0");
    }
    return hex;
  } catch (error) {
    throw new Error(`SHA-256 digest failed: ${error.message}`);
  }
}

// Example usage:
// hashSha256Browser("hello-world").then((digest) => console.log(digest));
  • crypto.subtle is asynchronous: Always await subtle.digest(...) and handle rejections cleanly.
  • Secure context requirement: In browsers, crypto.subtle is restricted on plain non-localhost http:// origins.

3. Portable Helper, Constant-Time Comparison, and MD5 Caveats

When sharing logic or comparing hashes (such as signature verification), avoid standard === string equality on secrets/MACs to prevent timing side-channel leaks—use crypto.timingSafeEqual in Node.js—and keep MD5 confined strictly to non-adversarial checksums:

// Constant-time comparison for equal-length hex digests in Node.js
import crypto from "node:crypto";

function safeEqualHexDigest(actualHex, expectedHex) {
  if (typeof actualHex !== "string" || typeof expectedHex !== "string") {
    throw new TypeError("Both digests must be strings.");
  }

  const normalizedActual = actualHex.trim().toLowerCase();
  const normalizedExpected = expectedHex.trim().toLowerCase();

  if (normalizedActual.length !== normalizedExpected.length) {
    return false;
  }

  try {
    const bufA = Buffer.from(normalizedActual, "hex");
    const bufB = Buffer.from(normalizedExpected, "hex");
    if (bufA.length === 0 || bufA.length !== bufB.length) {
      return false;
    }
    return crypto.timingSafeEqual(bufA, bufB);
  } catch {
    return false;
  }
}

// Example usage:
const sampleDigest = hashStringNode("payload-v1", "sha256");
console.log(safeEqualHexDigest(sampleDigest, sampleDigest)); // true
  • Normalize hex case before comparison: Hashing in Node/Web Crypto produces lowercase hex (0-9a-f), so normalize case consistently before comparing.
  • Keep MD5 out of security boundaries: Even if an external API requires an MD5 header or legacy ETag check, never rely on MD5 for tamper resistance or authentication.