Random Password Generator - Using crypto.getRandomValues

Hi - I’m building a Random Password Generator. Got most of the functionality figured out.

In my code, I have a function that uses Math.random (I found some code online and used it) to return a shuffled password string. I’ve tried changed the Math.random statement to Crypto but can’t get it to work. How can I change the shuffledString line to use Crypto instead of Math and get the same result.

function shuffleString(str, maxlength) {
var shuffledString = str.split(’’).sort(function(){return 0.5-Math.random()}).join(’’);
if (maxlength > 0) {
shuffledString = shuffledString.substr(0, maxlength);
}
return shuffledString;
}

Note: I’m using rules to adjust the number of uppercase, lowercase, numeric, and special characters that are included in the password string.

May have figured this out (thank god for the Internet?)…Not sure if it’s right - but it makes sense…

function cryptoRand()
{
const randomBuffer = new Uint32Array(1);
(window.crypto || window.msCrypto).getRandomValues(randomBuffer);
return ( randomBuffer[0] / (0xffffffff + 1) );
}

function shuffleString(str, maxlength) {

// var shuffledString = str.split(’’).sort(function(){return 0.5-Math.random()}).join(’’);

var shuffledString = str.split('').sort(function(){return 0.5-cryptoRand()}).join('');

if (maxlength > 0) {
    shuffledString = shuffledString.substr(0, maxlength);
}
return shuffledString;

}

This topic was automatically closed after 70 days. New replies are no longer allowed.