🎲 Password Entropy: How to Calculate and Enforce It Programmatically
Password Entropy: How to Calculate and Enforce It Programmatically
Password entropy is a quantitative measure of password strength. Instead of guessing whether a password is "strong enough," you can calculate its entropy and enforce a minimum threshold programmatically. Using a password manager like NordPass ensures all your generated passwords meet the highest entropy standards.
The Entropy Formula
Password entropy is calculated as:
E = L * log₂(C)
Where: - E = entropy in bits - L = password length - C = size of the character set used
Each bit of entropy doubles the number of guesses an attacker must try. A password with 40 bits of entropy requires 2⁴⁰ (about 1 trillion) guesses on average.
Implementation in Python
import math
import re
def calculate_entropy(password: str) -> float:
length = len(password)
# Determine effective character set size
charset_size = 0
if re.search(r'[a-z]', password):
charset_size += 26
if re.search(r'[A-Z]', password):
charset_size += 26
if re.search(r'[0-9]', password):
charset_size += 10
if re.search(r'[^a-zA-Z0-9]', password):
charset_size += 33 # Approximate printable special chars
if charset_size == 0:
return 0.0
return length * math.log2(charset_size)
def assess_password_strength(password: str) -> dict:
entropy = calculate_entropy(password)
if entropy < 30:
strength = 'Very Weak'
recommendation = 'Crackable in seconds. Use at least 10 characters.'
elif entropy < 40:
strength = 'Weak'
recommendation = 'Crackable in minutes. Use at least 12 characters.'
elif entropy < 60:
strength = 'Moderate'
recommendation = 'Adequate for low-risk accounts. Consider 14+ characters.'
elif entropy < 80:
strength = 'Strong'
recommendation = 'Good for most purposes.'
else:
strength = 'Very Strong'
recommendation = 'Effectively uncrackable by current standards.'
return {
'entropy_bits': round(entropy, 1),
'strength': strength,
'recommendation': recommendation,
'length': len(password)
}
Implementation in JavaScript
function calculateEntropy(password) {
const length = password.length;
let charsetSize = 0;
if (/[a-z]/.test(password)) charsetSize += 26;
if (/[A-Z]/.test(password)) charsetSize += 26;
if (/[0-9]/.test(password)) charsetSize += 10;
if (/[^a-zA-Z0-9]/.test(password)) charsetSize += 33;
if (charsetSize === 0) return 0;
return length * Math.log2(charsetSize);
}
Enforcing Minimum Entropy in APIs
from fastapi import FastAPI, HTTPException, Query
import secrets
app = FastAPI()
MIN_ENTROPY = 60 # NIST minimum for memorised secrets
@app.get("/api/validate")
async def validate_password(password: str = Query(...)):
result = assess_password_strength(password)
if result['entropy_bits'] < MIN_ENTROPY:
raise HTTPException(400, detail={
'message': 'Password does not meet minimum entropy requirement',
'minimum_entropy': MIN_ENTROPY,
'your_entropy': result['entropy_bits'],
'recommendation': result['recommendation']
})
return {'valid': True, 'entropy_bits': result['entropy_bits']}
Entropy vs. Guessability
Entropy calculations assume a purely random password. For human-chosen passwords, effective entropy is much lower due to dictionary words, patterns, and personal information. Always check generated passwords against breach databases in addition to entropy calculations.
When to Calculate Entropy
- Password creation: Reject passwords below minimum entropy
- Password generation: Log entropy of generated passwords as a quality metric
- Audit: Report entropy distribution across all user accounts
- Compliance: Demonstrate minimum entropy compliance for regulatory requirements