Since a password needs to be unpredictable, it needs to be generated by a well seeded crypto PRNG. Math.random
is usually not secure.
Modern browsers (At least the current versions of Firefox and Chrome) support window.crypto.getRandomValues
which generates secure random values.
Presto based Opera doesn't support it, but its Math.random
is secure. But since Opera has died, the fallback shouldn't be necessary anymore.
function randomString(length)
{
var charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var i;
var result = "";
var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
if(window.crypto && window.crypto.getRandomValues)
{
values = new Uint32Array(length);
window.crypto.getRandomValues(values);
for(i=0; i<length; i++)
{
result += charset[values[i] % charset.length];
}
return result;
}
else if(isOpera)//Opera's Math.random is secure, see http://lists.w3.org/Archives/Public/public-webcrypto/2013Jan/0063.html
{
for(i=0; i<length; i++)
{
result += charset[Math.floor(Math.random()*charset.length)];
}
return result;
}
else throw new Error("Your browser sucks and can't generate secure random numbers");
}
alert(randomString(10))
http://jsfiddle.net/ebbpa/