Javascript生成具有特定字母数的随机密码

时间:2013-08-08 05:54:46

标签: javascript security random passwords

我想在Javascript中在客户端的网页中生成密码。密码应使用字母和数字,也许是一些符号。如何安全地在Javascript中生成密码?

2 个答案:

答案 0 :(得分:7)

由于密码需要不可预测,因此需要由种子密码加密的PRNG生成。 Math.random通常不安全。

现代浏览器(至少当前版本的Firefox和Chrome)支持生成安全随机值的window.crypto.getRandomValues

基于Presto的Opera不支持它,但它的Math.random是安全的。但是,由于Opera已经去世,因此不再需要后备。

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/

答案 1 :(得分:-1)

 var random=Math.random().toString(36).substring(7);//this gives you 7 alpha numeric characters.
 var timestamp =new Date().getTime();//this gives you epoch time
 var my_very_unique_password=(random+timestamp);//concat both..
 alert(my_very_unique_password);

小提琴http://jsfiddle.net/bP57B/

如果您不想要这么大的密码,请执行alert(random)