Last active
January 18, 2023 16:23
-
-
Save iandunn/79acc38755033b2e94b81fb3ad3dfc4b to your computer and use it in GitHub Desktop.
Cryptographically secure random password using `crypto.getRandomValues`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ⚠️ I have not verified that this is secure; I just cleaned it up to try it out. | |
// Use at your own risk. I ended up using https://www.npmjs.com/package/@automattic/generate-password instead. | |
/** | |
* Generate a cryptographically secure random password in the browser. | |
* | |
* This is a modified version of https://stackoverflow.com/a/43020177/450127 that aims to | |
* to improve readability, and increase the length and character pool. The results should be | |
* the same as the original. | |
* | |
* @returns {string} | |
*/ | |
function generatePasswordInBrowser() { | |
const characterPool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()'; | |
const pwLength = 24; | |
const randomNumbers = new Uint32Array( 1 ); | |
const umax = Math.pow( 2, 32 ); | |
const max = umax - ( umax % characterPool.length ); | |
let password = new Array( pwLength ).fill( 0 ); | |
password = password.map( () => { | |
do { | |
crypto.getRandomValues( randomNumbers ); // Overwrite the existing numbers with new ones. | |
} while ( randomNumbers[ 0 ] > max ); | |
const randomPosition = randomNumbers[ 0 ] % characterPool.length; | |
return characterPool[ randomPosition ]; | |
} ); | |
password = password.join( '' ); | |
return password; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment