Back to cheatsheets
Passwords
Password Generation
Generate cryptographically secure passwords using the Web Crypto API with real entropy math.
What you'll learn
- Secure random password
- Entropy calculation
- Rejection sampling (no modulo bias)
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
- Try the interactive related tool to see the concept in action.
Code Snippets
Copy-paste code snippets
3 ready-to-use snippets for password generation. Click copy and paste into your project.
Secure random password
function generatePassword(len = 16, charset = 'A-Za-z0-9!@#$') {
const chars = charset.includes('A-Z')
? 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' : '';
const lower = charset.includes('a-z')
? 'abcdefghijklmnopqrstuvwxyz' : '';
const nums = charset.includes('0-9')
? '0123456789' : '';
const sym = charset.includes('!@#$')
? '!@#$%^&*()_+-=[]{}|;:,.<>?' : '';
const pool = chars + lower + nums + sym;
const arr = new Uint32Array(len);
crypto.getRandomValues(arr);
return Array.from(arr, n => pool[n % pool.length]).join('');
}
Entropy calculation
function entropyBits(charsetSize, length) {
return Math.log2(charsetSize) * length;
}
// 16 chars, 94 charset → 105 bits
entropyBits(94, 16); // 105.0
Rejection sampling (no modulo bias)
function secureRandomInt(max) {
const arr = new Uint32Array(1);
const limit = 0xFFFFFFFF - (0xFFFFFFFF % max);
do { crypto.getRandomValues(arr); }
while (arr[0] >= limit);
return arr[0] % max;
}
Tool
Related ShieldX tool
Try this concept hands-on with the interactive tool.
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site