Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to generate random password with specific number of letters [closed]

I want to generate a password in a web page, on the client side, in Javascript. The password should use letters and numbers, perhaps some symbols. How can I generate a password in Javascript securely?

like image 814
user2663270 Avatar asked Dec 04 '25 03:12

user2663270


1 Answers

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/

like image 178
CodesInChaos Avatar answered Dec 06 '25 18:12

CodesInChaos