Security & Utilities8 min technical readUpdated 2026-11-29

Browser Cryptography: SHA-256 Digests, CSPRNG UUID v4 & Password Bit Entropy

Cryptographic primitives fail silently when built on non-cryptographic PRNGs or misused for password storage. Explore SubtleCrypto SHA-256, RFC 9562 UUIDs, and unbiased secret generation.

By DevToolbox Engineering Team • Published by SummitStore Digital Products

How SHA-256 Works and Why Fast Hashes Must Not Store Passwords

SHA-256 (Secure Hash Algorithm 256-bit, standardized in NIST FIPS 180-4) processes arbitrary-length byte streams in 512-bit blocks through 64 rounds of bitwise rotations, XORs, and modular additions to produce a fixed 32-byte (64-hex-character) digest.

It exhibits the avalanche effect: flipping a single bit in a 10 MB input flips roughly half of the output bits unpredictably, making preimage reversal and collision crafting computationally infeasible.

Paradoxically, SHA-256's blazing hardware speed makes raw SHA-256 dangerous for hashing user passwords! Modern GPUs can evaluate tens of billions of unsalted SHA-256 hashes per second. Use SHA-256 for file checksums, Subresource Integrity (SRI), HMAC webhook signatures, and content-addressed storage—and always use memory-hard slow KDFs (Argon2id, bcrypt, or scrypt) for human passwords.

Computing a Hex SHA-256 Digest with Native Browser SubtleCrypto
export async function sha256Hex(message: string): Promise<string> {
  const bytes = new TextEncoder().encode(message);
  const digestBuffer = await crypto.subtle.digest("SHA-256", bytes);
  return Array.from(new Uint8Array(digestBuffer))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
}

Why Math.random() Is Broken for UUIDs, Tokens, and Keys

JavaScript's Math.random() uses an engine-specific non-cryptographic pseudo-random number generator (typically xorshift128+ in V8). Observing a handful of outputs allows an attacker to reconstruct the internal 128-bit state via Z3 SMT solvers and predict both future and past outputs!

By contrast, crypto.getRandomValues() and crypto.randomUUID() draw entropy directly from the operating system's Cryptographically Secure Pseudo-Random Number Generator (/dev/urandom on Linux, BCryptGenRandom on Windows, SecRandomCopyBytes on macOS/iOS). Every RFC 4122 / RFC 9562 Version 4 UUID carries 122 bits of true cryptographic randomness (with 6 fixed version/variant bits).

Shannon Bit Entropy and Eliminating Modulo Bias

True secret strength depends on the mathematical entropy of the generator, calculated as E = L × log2(N), where L is secret length and N is character pool size. A 16-character alphanumeric-plus-symbol password drawn uniformly from 88 characters yields ~103.3 bits of entropy, whereas a 32-byte hex API key (64 hex chars) yields 256 bits.

When mapping random uint32 integers onto a character set of size N (e.g., N = 88) using randomUint32 % N, values near 0 are slightly more likely whenever 2^32 is not evenly divisible by N (modulo bias). Rejection sampling discards any random integer >= floor(2^32 / N) * N and draws again, guaranteeing a mathematically uniform distribution.

Debugging Checksum Mismatches Across CLI and Web Tools

When sha256sum in a Linux terminal produces a different hash than a browser or Node.js script for the same text, 99% of the time echo appended a hidden trailing newline (0x0A). For example, 'abc' hashes to ba7816bf..., whereas 'abc\n' hashes to edeaaff3.... Always use printf '%s' 'abc' | sha256sum or echo -n when comparing test vectors.

Choosing the Right Cryptographic Primitive for Engineering Tasks

Engineering RequirementCorrect PrimitiveWrong ChoiceReason
File / bundle integrity (SRI)SHA-256 / SHA-384MD5 / CRC32MD5 collisions can be forged in seconds
Webhook authenticityHMAC-SHA256sha256(secret + body)Plain SHA-256 is vulnerable to length-extension
User password storageArgon2id / bcryptRaw SHA-256GPUs crack fast unsalted hashes at >20 GH/s
Primary keys / correlation IDscrypto.randomUUID() (v4/v7)Math.random() stringMath.random() state is predictable & collides

Production Engineering Checklist

  • Use crypto.subtle.digest('SHA-256', ...) for integrity digests and never for raw password storage.
  • Replace every security-sensitive or identifier use of Math.random() with crypto.randomUUID() or crypto.getRandomValues().
  • Use rejection sampling when mapping random bytes onto non-power-of-two alphabets.
  • Aim for >= 80 bits of entropy for user passwords and >= 128–256 bits for machine API keys and JWT signing secrets.

Frequently Asked Questions

What is the collision probability of UUID v4?

With 122 random bits (5.3 × 10^36 possible values), you would need to generate roughly 2.71 quintillion (2.71 × 10^18) UUIDs to reach a 50% probability of a single collision.

Why does crypto.subtle require HTTPS or localhost?

W3C restricts Web Crypto's SubtleCrypto interface to Secure Contexts (HTTPS and localhost) so network attackers on unencrypted HTTP cannot tamper with the JavaScript code performing cryptographic operations.