DEV Community

黃彥鈞
黃彥鈞

Posted on

Stop Using Math.random() for Secrets: Build a Zero-Server Password & SHA-256 Tool with Web Crypto

Whenever you need a fresh API webhook secret, .env signing key, or high-entropy passphrase, pasting secrets into a random web generator is a risk—and Math.random() is not cryptographically secure.

Every modern browser ships with the built-in Web Crypto API (crypto.getRandomValues + crypto.subtle.digest), which gives you CSPRNG-grade randomness and hardware-accelerated SHA-256 hashing with zero npm dependencies and zero server calls.

1. Unbiased Cryptographic Password Generator (12 Lines)

Avoid the classic modulo-bias bug (randomByte % charset.length) by rejecting values outside the largest clean multiple:

export function generateSecureSecret(length = 24) {
  const charset = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*_-+=';
  const maxValid = Math.floor(256 / charset.length) * charset.length;
  const result = [];
  const buf = new Uint8Array(length * 2);

  while (result.length < length) {
    crypto.getRandomValues(buf);
    for (const byte of buf) {
      if (byte < maxValid && result.length < length) {
        result.push(charset[byte % charset.length]);
      }
    }
  }
  return result.join('');
}
Enter fullscreen mode Exit fullscreen mode

2. Instant Client-Side SHA-256 Checksum

export async function sha256Hex(text) {
  const bytes = new TextEncoder().encode(text);
  const hashBuffer = await crypto.subtle.digest('SHA-256', bytes);
  return Array.from(new Uint8Array(hashBuffer))
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('');
}
Enter fullscreen mode Exit fullscreen mode

Ready-to-Use Offline Browser Version

I wrapped this exact Web Crypto logic—plus entropy bit calculation and SHA-256/SHA-512 checksums—into a zero-login, zero-network tool:

Do you keep a local CLI snippet for generating secrets, or use a password manager?

Top comments (0)