Javascript生成具有特定字母数的随机密码
我想在Javascript中在客户端的网页中生成密码。密码应使用字母和数字,也许是一些符号。如何安全地在Javascript中生成密码?
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?
由于密码需要不可预测,因此需要由密码生成种子密码加密PRNG。 Math.random
通常不安全。
Since a password needs to be unpredictable, it needs to be generated by a well seeded crypto PRNG. Math.random
is usually not secure.
现代浏览器(至少支持当前版本的Firefox和Chrome) window.crypto.getRandomValues
,它会生成安全的随机值。
Modern browsers (At least the current versions of Firefox and Chrome) support window.crypto.getRandomValues
which generates secure random values.
基于Presto的Opera不支持它,但它的 Math.random
是安全的。但是,由于Opera已经去世,因此不再需要后备。
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/