什么是创建一个包含8个字符的随机密码的最佳方法a-z,A-Z以及0-9?
绝对没有安全问题,这仅是用于原型制作,我只希望看起来真实的数据。
我当时正在考虑for (0 to 7) Math.random产生ASCII码并将其转换为字符。你有什么其他的建议?
什么是创建一个包含8个字符的随机密码的最佳方法a-z,A-Z以及0-9?
绝对没有安全问题,这仅是用于原型制作,我只希望看起来真实的数据。
我当时正在考虑for (0 to 7) Math.random产生ASCII码并将其转换为字符。你有什么其他的建议?
Answers:
我可能会使用这样的东西:
function generatePassword() {
var length = 8,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
然后可以将其扩展为通过参数传递长度和字符集。
Math.random() * n。除此之外,它可以完美运行,并且正如您所说,很容易修改。谢谢(:
floor是没有必要的。在这种情况下,它将9无法获得。
这是我知道的最快,最简单的方法:
Math.random().toString(36).slice(2)
这个想法是将一个随机数(在0..1范围内)强制转换为base36字符串(小写az加0-9),并删除前导零和小数点。
请注意,所有伪生成的密码都有某种形式的漏洞。但是,我要说的是,对于所有常规用例而言,它已经足够了。此外,如果不能保证此密码,则为理论长度。最多16个字符,最小0个字符。循环运行一百万次后,其平均长度为15.67个字符,最小长度为5。但是,如果将其中两个密码结合在一起,则将获得最大长度为32个字符,平均长度为31.33个字符和一个最小长度为20。
Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2)
我个人将其用作bookmarklet浏览器书签栏中的镶边,以快速生成密码:
javascript:(
function(){
prompt('Here is your shiny new password:',
Math.random().toString(36).slice(2) +
Math.random().toString(36).slice(2)
);
}
)();
Math.random().toString(36) + Math.random().toString(36).toUpperCase()解决该问题。另外,您还将获得两个小数点,因此也解决了所有特殊字符要求。我已经对此做出了最初的回答:javascript:(function(){prompt('Here is your shiny new password:',(Math.random().toString(36)+Math.random().toString(36).toUpperCase()).split('').sort(function(){return 0.5-Math.random()}).join(''));return false;})();唯一的区别在于,除了toUpperCase之外split('').sort().join('')。
function password_generator( len ) {
var length = (len)?(len):(10);
var string = "abcdefghijklmnopqrstuvwxyz"; //to upper
var numeric = '0123456789';
var punctuation = '!@#$%^&*()_+~`|}{[]\:;?><,./-=';
var password = "";
var character = "";
var crunch = true;
while( password.length<length ) {
entity1 = Math.ceil(string.length * Math.random()*Math.random());
entity2 = Math.ceil(numeric.length * Math.random()*Math.random());
entity3 = Math.ceil(punctuation.length * Math.random()*Math.random());
hold = string.charAt( entity1 );
hold = (password.length%2==0)?(hold.toUpperCase()):(hold);
character += hold;
character += numeric.charAt( entity2 );
character += punctuation.charAt( entity3 );
password = character;
}
password=password.split('').sort(function(){return 0.5-Math.random()}).join('');
return password.substr(0,len);
}
console.log( password_generator() );
这将生成更健壮的密码,该密码应通过任何密码强度测试。如:f1&d2?I4(h1&,C1^y1)j1@G2#,j2{h6%b5@R2)
(entity1 % 2 == 0)与字符串相同,则为:AbCdEfGhIjKl...。也m丢失了,密码长度始终为len - len%3 + 3(例如:
function generatePass(pLength){
var keyListAlpha="abcdefghijklmnopqrstuvwxyz",
keyListInt="123456789",
keyListSpec="!@#_",
password='';
var len = Math.ceil(pLength/2);
len = len - 1;
var lenSpec = pLength-2*len;
for (i=0;i<len;i++) {
password+=keyListAlpha.charAt(Math.floor(Math.random()*keyListAlpha.length));
password+=keyListInt.charAt(Math.floor(Math.random()*keyListInt.length));
}
for (i=0;i<lenSpec;i++)
password+=keyListSpec.charAt(Math.floor(Math.random()*keyListSpec.length));
password=password.split('').sort(function(){return 0.5-Math.random()}).join('');
return password;
}
如果您的lodash> = 4.0,那么有一种更优雅的方法
var chars = 'abcdefghkmnpqrstuvwxyz23456789';
function generatePassword(length) {
return _.sampleSize(chars, length).join('');
}
chars。对于更长的字符串,请重新采样chars。
Gumbo的解决方案不起作用。不过,这是这样做的:
function makePasswd() {
var passwd = '';
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (i=1;i<8;i++) {
var c = Math.floor(Math.random()*chars.length + 1);
passwd += chars.charAt(c)
}
return passwd;
}
a和之间获得随机字符9...我猜charAt会自动出现floor或是round浮点数。
这是一个为您提供更多选项的功能,用于设置特殊字符的最小值,较高字符的最小值,较低字符的最小值和数量的最小值
function randomPassword(len = 8, minUpper = 0, minLower = 0, minNumber = -1, minSpecial = -1) {
let chars = String.fromCharCode(...Array(127).keys()).slice(33),//chars
A2Z = String.fromCharCode(...Array(91).keys()).slice(65),//A-Z
a2z = String.fromCharCode(...Array(123).keys()).slice(97),//a-z
zero2nine = String.fromCharCode(...Array(58).keys()).slice(48),//0-9
specials = chars.replace(/\w/g, '')
if (minSpecial < 0) chars = zero2nine + A2Z + a2z
if (minNumber < 0) chars = chars.replace(zero2nine, '')
let minRequired = minSpecial + minUpper + minLower + minNumber
let rs = [].concat(
Array.from({length: minSpecial ? minSpecial : 0}, () => specials[Math.floor(Math.random() * specials.length)]),
Array.from({length: minUpper ? minUpper : 0}, () => A2Z[Math.floor(Math.random() * A2Z.length)]),
Array.from({length: minLower ? minLower : 0}, () => a2z[Math.floor(Math.random() * a2z.length)]),
Array.from({length: minNumber ? minNumber : 0}, () => zero2nine[Math.floor(Math.random() * zero2nine.length)]),
Array.from({length: Math.max(len, minRequired) - (minRequired ? minRequired : 0)}, () => chars[Math.floor(Math.random() * chars.length)]),
)
return rs.sort(() => Math.random() > Math.random()).join('')
}
randomPassword(12, 1, 1, -1, -1)// -> DDYxdVcvIyLgeB
randomPassword(12, 1, 1, 1, -1)// -> KYXTbKf9vpMu0
randomPassword(12, 1, 1, 1, 1)// -> hj|9)V5YKb=7
这是一个简单的智能代码:
function generate(l) {
if (typeof l==='undefined'){var l=8;}
/* c : alphanumeric character string */
var c='abcdefghijknopqrstuvwxyzACDEFGHJKLMNPQRSTUVWXYZ12345679',
n=c.length,
/* p : special character string */
p='!@#$+-*&_',
o=p.length,
r='',
n=c.length,
/* s : determinate the position of the special character */
s=Math.floor(Math.random() * (p.length-1));
for(var i=0; i<l; ++i){
if(s == i){
/* special charact insertion (random position s) */
r += p.charAt(Math.floor(Math.random() * o));
}else{
/* alphanumeric insertion */
r += c.charAt(Math.floor(Math.random() * n));
}
}
return r;
}
只需调用generate(),它就会执行包含一个特殊字符(!@#$ +-** _)的密钥以确保安全。
可能的结果:WJGUk $ Ey,gaV7#fF7,ty_T55DD,YtrQMWveZqYyYKo_
我的网站上有更多详细信息和示例:https : //www.bxnxg.com/minituto-01-generer-mots-de-passes-secures-facilements-zh-javascript/
甚至更短:
Array.apply(null, Array(8)).map(function() {
var c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
return c.charAt(Math.random() * c.length);
}).join('');
或作为功能:
function generatePassword(length, charSet) {
charSet = charSet ? charSet : 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789^°!"§$%&/()=?`*+~\'#,;.:-_';
return Array.apply(null, Array(length || 10)).map(function() {
return charSet.charAt(Math.random() * charSet.length);
}).join('');
}
为每个字符随机分配字母,数字,大写字母和特殊字符,然后验证密码。如果不包含上述所有内容,则从丢失的元素中随机分配一个新字符给一个随机的现有字符,然后递归验证直到形成密码:
function createPassword(length) {
var alpha = "abcdefghijklmnopqrstuvwxyz";
var caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numeric = "0123456789";
var special = "!$^&*-=+_?";
var options = [alpha, caps, numeric, special];
var password = "";
var passwordArray = Array(length);
for (i = 0; i < length; i++) {
var currentOption = options[Math.floor(Math.random() * options.length)];
var randomChar = currentOption.charAt(Math.floor(Math.random() * currentOption.length));
password += randomChar;
passwordArray.push(randomChar);
}
checkPassword();
function checkPassword() {
var missingValueArray = [];
var containsAll = true;
options.forEach(function (e, i, a) {
var hasValue = false;
passwordArray.forEach(function (e1, i1, a1) {
if (e.indexOf(e1) > -1) {
hasValue = true;
}
});
if (!hasValue) {
missingValueArray = a;
containsAll = false;
}
});
if (!containsAll) {
passwordArray[Math.floor(Math.random() * passwordArray.length)] = missingValueArray.charAt(Math.floor(Math.random() * missingValueArray.length));
password = "";
passwordArray.forEach(function (e, i, a) {
password += e;
});
checkPassword();
}
}
return password;
}
这是基于Stephan Hoyer解决方案的另一种方法
getRandomString (length) {
var chars = 'abcdefghkmnpqrstuvwxyz23456789';
return times(length, () => sample(chars)).join('');
}
return times(length, () => sample(chars)).join('');
function genPass(n) // e.g. pass(10) return 'unQ0S2j9FY'
{
let c='abcdefghijklmnopqrstuvwxyz'; c+=c.toUpperCase()+1234567890;
return [...Array(n)].map(b=>c[~~(Math.random()*62)]).join('')
}
其中n输出密码字符数; 62是c.length,例如~~4.5 = 4替换的窍门Math.floor
function genPass(n) // e.g. pass(10) return 'unQ0S2j9FY'
{
let c='abcdefghijklmnopqrstuvwxyz'; c+=c.toUpperCase()+1234567890;
return '-'.repeat(n).replace(/./g,b=>c[~~(Math.random()*62)])
}
要扩展字符列表,请将它们添加到,c例如,添加10个字符!$^&*-=+_?写入c+=c.toUpperCase()+1234567890+'!$^&*-=+_?'并更改Math.random()*62为Math.random()*72(添加10至62)。
此方法提供用于更改密码大小和字符集的选项。
function generatePassword(length=8, charset="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
return new Array(length)
.fill(null)
.map(()=> charset.charAt(Math.floor(Math.random() * charset.length)))
.join('');
}
console.log(generatePassword()); // 02kdFjzX
console.log(generatePassword(4)); // o8L5
console.log(generatePassword(16)); // jpPd7S09txv9b02p
console.log(generatePassword(16, "abcd1234")); // 4c4d323a31c134dd
我的痛点是每个注册工具都允许使用不同的特殊字符集。有些人可能只允许这些,@#$%&*而另一些人可能不允许,*但确实允许其他事情。当遇到特殊字符时,我遇到的每个密码生成器都是二进制的。它允许您包含或不包含它们。因此,我最终遍历了众多选项,并扫描了不符合要求的异常值,直到找到有效的密码。密码越长,密码就越繁琐。最后,我注意到有时候注册工具不允许您连续两次重复相同的字符,但是密码生成器似乎无法解决这个问题。疯了!
我自己做了这个,所以我可以粘贴允许的确切字符集。我不假装这是优雅的代码。我只是把它放在一起以满足我的需要。
另外,我想不起来注册工具不允许数字或不区分大小写,因此我的密码始终至少包含一个数字,一个大写字母,一个小写字母和一个特殊字符。这意味着最小长度为4。从技术上讲,我可以通过输入字母来解决特殊字符的要求。
const getPassword = (length, arg) => {
length = document.getElementById("lengthInput").value || 16;
arg = document.getElementById("specialInput").value || "~!@#$%^&*()_+-=[]{}|;:.,?><";
if (length < 4) {
updateView("passwordValue", "passwordValue", "", "P", "Length must be at least 4");
return console.error("Length must be at least 4")
} else if (length > 99) {
updateView("passwordValue", "passwordValue", "", "P", "Length must be less then 100");
return console.error("Length must be less then 100")
}
const lowercase = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
const uppercase = lowercase.join("").toUpperCase().split("");
const specialChars = arg.split("").filter(item => item.trim().length);
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let hasNumber = false;
let hasUpper = false;
let hasLower = false;
let hasSpecial = false;
if (Number(length)) {
length = Number(length)
} else {
return console.error("Enter a valid length for the first argument.")
}
let password = [];
let lastChar;
for (let i = 0; i < length; i++) {
let char = newChar(lowercase, uppercase, numbers, specialChars);
if (char !== lastChar) {
password.push(char);
lastChar = char
if (Number(char)) {
hasNumber = true
}
if (lowercase.indexOf(char) > -1) {
hasLower = true
}
if (uppercase.indexOf(char) > -1) {
hasUpper = true
}
if (specialChars.indexOf(char) > -1) {
hasSpecial = true
}
} else {
i--
}
if (i === length - 1 && (!hasNumber || !hasUpper || !hasLower || !hasSpecial)) {
hasNumber = false;
hasUpper = false;
hasLower = false;
hasSpecial = false;
password = [];
i = -1;
}
}
function newChar(lower, upper, nums, specials) {
let set = [lower, upper, nums, specials];
let pick = set[Math.floor(Math.random() * set.length)];
return pick[Math.floor(Math.random() * pick.length)]
}
updateView("passwordValue", "passwordValue", "", "P", password.join(""));
updateView("copyPassword", "copyPassword", "", "button", "copy text");
document.getElementById("copyPassword").addEventListener("click", copyPassword);
}
const copyPassword = () => {
let text = document.getElementById("passwordValue").textContent;
navigator.clipboard.writeText(text);
};
const updateView = (targetId, newId, label, element, method = '') => {
let newElement = document.createElement(element);
newElement.id = newId;
let content = document.createTextNode(label + method);
newElement.appendChild(content);
let currentElement = document.getElementById(targetId);
let parentElement = currentElement.parentNode;
parentElement.replaceChild(newElement, currentElement);
}
document.getElementById("getPassword").addEventListener("click", getPassword);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<button id="getPassword">Generate Password</button>
<input type="number" id="lengthInput" placeholder="Length">
<input type="text" id="specialInput" placeholder="Special Characters">
<p id="passwordValue"></p>
<p id="copyPassword"></p>
</div>
</body>
</html>
我在此页面上看到许多使用Math.random的示例。此方法没有加密强随机值,因此不安全。相反,建议使用Math.random使用getRandomValues或您自己的算法。
您可以使用passfather。这是一个使用加密强度很高的算法的程序包。我是此套餐的所有者,因此您可以提出一些问题。
生成带有密码的密码的代码将被赋予长度(默认为8),并且至少包含一个大写字母,一个小写字母,一个数字和一个符号
(2个函数和一个称为“ allowed”的const变量)
const allowed = {
uppers: "QWERTYUIOPASDFGHJKLZXCVBNM",
lowers: "qwertyuiopasdfghjklzxcvbnm",
numbers: "1234567890",
symbols: "!@#$%^&*"
}
const getRandomCharFromString = (str) => str.charAt(Math.floor(Math.random() * str.length))
const generatePassword = (length = 8) => { // password will be @Param-length, default to 8, and have at least one upper, one lower, one number and one symbol
let pwd = "";
pwd += getRandomCharFromString(allowed.uppers); //pwd will have at least one upper
pwd += getRandomCharFromString(allowed.lowers); //pwd will have at least one lower
pwd += getRandomCharFromString(allowed.numbers); //pwd will have at least one number
pwd += getRandomCharFromString(allowed.symbols);//pwd will have at least one symbolo
for (let i = pwd.length; i < length; i++)
pwd += getRandomCharFromString(Object.values(allowed).join('')); //fill the rest of the pwd with random characters
return pwd
}
这是一个免费的,可配置的Java类,可生成随机密码:Javascript Random Password Generator。
例子
密码由小写+大写+数字组成,长度为8个字符:
var randomPassword = new RandomPassword();
document.write(randomPassword.create());
密码由小写字母+大写字母+数字组成,长度为20个字符:
var randomPassword = new RandomPassword();
document.write(randomPassword.create(20));
密码由小写+大写+数字+符号组成,长度为20个字符:
var randomPassword = new RandomPassword();
document.write(randomPassword.create(20,randomPassword.chrLower+randomPassword.chrUpper+randomPassword.chrNumbers+randomPassword.chrSymbols));
var createPassword = function() {
var passAt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
var passArray = Array.from({length: 15})
return passArray.map(function(_, index) {
return index % 4 == 3 ? '-' : passAt.charAt(Math.random() * passAt.length)
}).join('')
}
结果像:
L5X-La0-bN0-UQO
9eW-svG-OdS-8Xf
ick-u73-2s0-TMX
5ri-PRP-MNO-Z1j
这是一个快速动态的现代解决方案,我想我会分享
const generatePassword = (
passwordLength = 8,
useUpperCase = true,
useNumbers = true,
useSpecialChars = true,
) => {
const chars = 'abcdefghijklmnopqrstuvwxyz'
const numberChars = '0123456789'
const specialChars = '!"£$%^&*()'
const usableChars = chars
+ (useUpperCase ? chars.toUpperCase() : '')
+ (useNumbers ? numberChars : '')
+ (useSpecialChars ? specialChars : '')
let generatedPassword = ''
for(i = 0; i <= passwordLength; i++) {
generatedPassword += usableChars[Math.floor(Math.random() * (usableChars.length))]
}
return generatedPassword
}
一个简单的lodash解决方案,保证14个字母,3个数字和3个特殊字符,不再重复:
const generateStrongPassword = (alpha = 14, numbers = 3, special = 3) => {
const alphaChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numberChars = '0123456789';
const specialChars = '!"£$%^&*()-=+_?';
const pickedChars = _.sampleSize(alphaChars, alpha)
.concat(_.sampleSize(numberChars, numbers))
.concat(_.sampleSize(specialChars, special));
return _.shuffle(pickedChars).join('');
}
const myPassword = generateStrongPassword();
const length = 18; // you can use length as option or static
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const numbers = '0123456789';
const symbols = '!#$%&\()*+,-./:;<=>?@^[\\]^_`{|}~';
let password = '';
let validChars = '';
// all if conditions can be used to custom password
if (useLetters) {
validChars += letters;
}
if (useNumbers) {
validChars += numbers;
}
if (useSymbols) {
validChars += symbols;
}
let generatedPassword = '';
for (let i = 0; i < length; i++) {
const index = Math.floor(Math.random() * validChars.length);
generatedPassword += validChars[index];
}
password = generatedPassword;
function genPass(){
//https://sita.app/password-generator
let stringInclude = '';
stringInclude += "!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~";
stringInclude += '0123456789';
stringInclude += 'abcdefghijklmnopqrstuvwxyz';
stringInclude += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var password ='';
for (let i = 0; i < 40; i++) {
password += stringInclude.charAt(Math.floor(Math.random() * stringInclude.length));
}
return password;
}
我还开发了自己的密码生成器,该密码生成器具有随机长度(默认情况下介于16到40之间),强密码,也许有帮助。
function randomChar(string) {
return string[Math.floor(Math.random() * string.length)];
}
// you should use another random function, like the lodash's one.
function random(min = 0, max = 1) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// you could use any shuffle function, the lodash's one, or the following https://stackoverflow.com/a/6274381/6708504
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
function generatePassword() {
const symbols = '§±!@#$%^&*()-_=+[]{}\\|?/<>~';
const numbers = '0123456789';
const lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz';
const uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const minCharsGroup = 4;
const maxCharsGroup = 10;
const randomSymbols = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(symbols));
const randomNumbers = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(numbers));
const randomUppercasesLetters = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(uppercaseLetters));
const randomLowercasesLetters = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(lowercaseLetters));
const chars = [...randomSymbols, ...randomNumbers, ...randomUppercasesLetters, ...randomLowercasesLetters];
return shuffle(chars).join('');
}
这是我找到的解决方案,如果您查看页面的源代码,则还可以看到它们如何实现示例:
https://www.404it.no/zh-CN/blog/javascript_random_password_generator
Javascript随机密码生成器发布:2015年1月6日更新:2015年1月18日作者:Per Kristian Haakonsen