Skip to content

Instantly share code, notes, and snippets.

@iandunn
Last active January 18, 2023 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iandunn/79acc38755033b2e94b81fb3ad3dfc4b to your computer and use it in GitHub Desktop.
Save iandunn/79acc38755033b2e94b81fb3ad3dfc4b to your computer and use it in GitHub Desktop.
Cryptographically secure random password using `crypto.getRandomValues`
// ⚠️ 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