Password Entropy and Cryptographic Randomness: A Developer Guide
Creating secure credentials, API keys, and server secrets requires a thorough understanding of cryptographic randomness and password strength metrics like entropy.
In this guide, we'll explain how password entropy is calculated, why native mathematical random functions are insecure for authentication, and how cryptographically secure random number generators work.
What is Password Entropy?
Entropy is a measure of the unpredictability of a password or secret. It represents the number of guesses a brute-force attacker would need to make to guarantee finding the password.
Entropy is measured in bits. The higher the entropy, the more secure the password is.
The formula for password entropy is:
$$E = L \times \log_2(R)$$
Where:
- $E$ is the entropy in bits.
- $L$ is the length of the password.
- $R$ is the size of the character pool (charset) being selected from.
Character Pool Sizes ($R$):
- Lowercase letters (
a-z): 26 characters - Uppercase letters (
A-Z): 26 characters - Numbers (
0-9): 10 characters - Standard symbols (
!@#$%^&*): 8 characters
If a password is 16 characters long and draws from all of these character groups ($R = 70$), its entropy is:
$$E = 16 \times \log_2(70) \approx 98 \text{ bits}$$
Password Generator
Generate strong, random, and cryptographically secure passwords online. Customize length, uppercase, lowercase, numbers, and symbols client-side.
Entropy Recommendations
- < 40 bits: Very Weak. Easily cracked in seconds by automated scripts.
- 40 - 59 bits: Weak/Fair. Vulnerable to offline brute-force attacks.
- 60 - 79 bits: Strong. Sufficient for standard user logins.
- 80+ bits: Very Strong. Recommended for critical admin accounts, server secrets, and API tokens.
Math.random() vs. CSPRNG
Many beginner developers use Math.random() to generate random passwords. This is a critical security vulnerability.
- Pseudo-Random Number Generators (PRNGs) like JavaScript's
Math.random()are designed for speed and visual randomness (e.g. game elements, animations). They are deterministic, meaning that if an attacker learns the internal state (the seed), they can predict all future generated values. - Cryptographically Secure Pseudo-Random Number Generators (CSPRNGs) utilize hardware-based entropy (like mouse movements, system interrupts, or hardware noise) to seed their algorithms. They are designed to prevent state recovery, meaning that even if an attacker intercepts a password, they cannot determine the next value.
Secure Randomness in Javascript
In web browsers, you should use the Web Crypto API's window.crypto.getRandomValues() method instead of Math.random().
Here is a secure implementation:
function generateSecureRandomBytes(length) {
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
return array;
}This ensures that the numbers generated are cryptographically secure and suitable for production passwords and API keys.