Password Strength By Entropy

Estimate password entropy from character pools, unique characters and common patterns to produce a five-level score.

JavascriptForm Validation

Code

snippet
const COMMON_PATTERNS = [/^123456/, /password/i, /qwerty/i, /(.)\1{2,}/];

// Password strength estimation based on character-pool entropy.
export function estimatePasswordStrength(password) {
  const value = String(password);
  const pools = [
    [/[a-z]/, 26],
    [/[A-Z]/, 26],
    [/[0-9]/, 10],
    [/[^A-Za-z0-9]/, 33],
  ];
  const poolSize = pools.reduce((total, [pattern, size]) => {
    return total + (pattern.test(value) ? size : 0);
  }, 0);
  const unique = new Set(value).size;
  const effectiveLength = Math.max(unique, Math.ceil(value.length * 0.75));
  let entropyBits = poolSize > 0 ? effectiveLength * Math.log2(poolSize) : 0;
  for (const pattern of COMMON_PATTERNS) {
    if (pattern.test(value)) entropyBits *= 0.5;
  }
  if (value.length < 8) entropyBits *= 0.6;
  const thresholds = [20, 40, 60, 80];
  let score = thresholds.filter((threshold) => entropyBits >= threshold).length;
  if (value.length === 0) score = 0;
  const labels = ["very weak", "weak", "fair", "strong", "very strong"];
  return {
    entropyBits: Math.round(entropyBits),
    score,
    label: labels[score],
    poolSize,
    length: value.length,
    uniqueCharacters: unique,
  };
}