创建包含a-z
,A-Z
和0-9
的8个字符随机密码的最佳方法是什么?
绝对没有安全问题,这只是用于原型设计,我只想要看起来真实的数据。
我在想for (0 to 7) Math.random
生成ASCII码并将它们转换为字符。你还有其他建议吗?
答案 0 :(得分:124)
我可能会使用这样的东西:
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;
}
然后可以将其扩展为通过参数传递长度和字符集。
答案 1 :(得分:25)
这是我所知道的最快捷,最简单的方式:
Math.random().toString(36).slice(2)
这个想法是将一个随机数(在0..1范围内)转换为base36字符串(小写字母a-z加0-9)并删除前导零和小数点。
请注意所有伪生成的密码都有某种形式的漏洞。但是,我会说它对所有正常使用情况都足够好。此外,如果此密码不保证,理论长度。最多16个字符,最少0个字符。当循环运行100万次时,其平均长度为15.67个字符,最小长度为5.但是,如果将其中两个密码连接在一起,则最大长度为32个字符,平均长度为31.33个字符和一个最小长度为20。
Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2)
我个人在浏览器书签栏中将其用作chrome bookmarklet
以快速生成密码:
javascript:(
function(){
prompt('Here is your shiny new password:',
Math.random().toString(36).slice(2) +
Math.random().toString(36).slice(2)
);
}
)();
答案 2 :(得分:21)
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)
答案 3 :(得分:11)
function generatePass(plength){
var keylistalpha="abcdefghijklmnopqrstuvwxyz";
var keylistint="123456789";
var keylistspec="!@#_";
var temp='';
var len = plength/2;
var len = len - 1;
var lenspec = plength-len-len;
for (i=0;i<len;i++)
temp+=keylistalpha.charAt(Math.floor(Math.random()*keylistalpha.length));
for (i=0;i<lenspec;i++)
temp+=keylistspec.charAt(Math.floor(Math.random()*keylistspec.length));
for (i=0;i<len;i++)
temp+=keylistint.charAt(Math.floor(Math.random()*keylistint.length));
temp=temp.split('').sort(function(){return 0.5-Math.random()}).join('');
return temp;
}
答案 4 :(得分:7)
这是我生成8个字符加密随机密码的函数:
function generatePassword() {
var buf = new Uint8Array(6);
window.crypto.getRandomValues(buf);
return btoa(String.fromCharCode.apply(null, buf));
}
它的作用:检索6个加密随机的8位整数,并用Base64对它们进行编码。
由于结果是Base64字符集,因此生成的密码可能包含A
- Z
,a
- z
,0
- {{ 1}},9
和+
。
答案 5 :(得分:5)
如果你有lodash&gt; = 4.0,那就有更优雅的方式
var chars = 'abcdefghkmnpqrstuvwxyz23456789';
function generatePassword(length) {
return _.sampleSize(chars, length).join('');
}
答案 6 :(得分:3)
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;
}
答案 7 :(得分:3)
如果字符[\]^_
正常,这将生成一个真实的密码。需要lodash和es7
String.fromCodePoint(...range(8).map(() => Math.floor(Math.random() * 57) + 0x41))
这里没有lodash
String.fromCodePoint(...Array.from({length: 8}, () => Math.floor(Math.random() * 57) + 65))
答案 8 :(得分:2)
这是一个简单的智能代码:
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(),它就会包含一个特殊字符(!@#$ + - *&amp; _)以确保安全性。
可能的结果:WJGUk $ Ey,gaV7#fF7,ty_T55DD,YtrQMWveZqYyYKo _
我的网站上有更多详情和示例:https://www.bxnxg.com/minituto-01-generer-mots-de-passes-secures-facilements-en-javascript/
答案 9 :(得分:2)
我受到上述答案的启发(尤其是来自@e.vyushin 关于 Math.random() 安全性的提示),我想出了以下使用 crypto.getRandomValues() 生成 rondom 的解决方案带有密码长度的 UInt32 值数组。
然后,它遍历数组并将每个元素除以 2^32(UInt32 的最大值)以计算实际值与最大值之间的比率。可能的价值。然后将该比率映射到字符集字符串以确定选择字符串的哪个字符。
console.log(createPassword(16,"letters+numbers+signs"));
function createPassword(len, charset) {
if (charset==="letters+numbers") {
var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
} else if (charset==="letters+numbers+signs") {
var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!§$%&/?#+-_@";
}
var arr = new Uint32Array(len);
var maxRange = Math.pow(2,32);
var passwd = '';
window.crypto.getRandomValues(arr);
for (let i=0;i<len;i++) {
var c = Math.floor(arr[i] / maxRange * chars.length + 1);
passwd += chars.charAt(c);
}
return passwd;
}
因此,代码能够利用加密类的优势(提高了随机值生成的安全性),并且可以适应使用用户希望的任何类型的字符集。下一步是使用正则表达式字符串来定义要使用的字符集。
答案 10 :(得分:2)
这是一个函数,为您提供更多选项来设置特殊字符的最小值,上部字符的最小值,较低字符的最小值和数字的最小值
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
答案 11 :(得分:1)
随机分配Alpha,Numeric,Caps和Special per characters然后验证密码。如果它不包含上述每一个,则从缺失元素中随机分配一个新字符到一个随机存在的字符,然后递归验证,直到形成密码:
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;
}
答案 12 :(得分:1)
我的痛点是每个注册工具都允许使用不同的特殊字符集。有些人可能只允许使用这些@#$%&*
,而另一些人可能不允许使用*
,但允许其他事情。当遇到特殊字符时,我遇到的每个密码生成器都是二进制的。它允许您包含或不包含它们。因此,我最终遍历了众多选项,并扫描了不符合要求的异常值,直到找到有效的密码。密码越长,密码就越繁琐。最后,我注意到有时候注册工具不允许您连续两次重复相同的字符,但是密码生成器似乎无法解决这个问题。疯了!
我是为自己制作的,因此我只能粘贴允许的确切特殊字符集。我不假装这是精美的代码。我只是把它放在一起以满足我的需要。
此外,我想不起来注册工具不允许数字或不区分大小写,因此我的密码始终至少包含一个数字,一个大写字母,一个小写字母和一个特殊字符。这意味着最小长度为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>
答案 13 :(得分:1)
我还开发了自己的密码生成器,长度随机(默认在 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('');
}
答案 14 :(得分:1)
生成长度为 8 到 32 个字符的随机密码,其中至少包含 1 个小写字母、1 个大写字母、1 个数字、1 个特殊字符 (!@$&)
function getRandomUpperCase() {
return String.fromCharCode( Math.floor( Math.random() * 26 ) + 65 );
}
function getRandomLowerCase() {
return String.fromCharCode( Math.floor( Math.random() * 26 ) + 97 );
}
function getRandomNumber() {
return String.fromCharCode( Math.floor( Math.random() * 10 ) + 48 );
}
function getRandomSymbol() {
// const symbol = '!@#$%^&*(){}[]=<>/,.|~?';
const symbol = '!@$&';
return symbol[ Math.floor( Math.random() * symbol.length ) ];
}
const randomFunc = [ getRandomUpperCase, getRandomLowerCase, getRandomNumber, getRandomSymbol ];
function getRandomFunc() {
return randomFunc[Math.floor( Math.random() * Object.keys(randomFunc).length)];
}
function generatePassword() {
let password = '';
const passwordLength = Math.random() * (32 - 8) + 8;
for( let i = 1; i <= passwordLength; i++ ) {
password += getRandomFunc()();
}
//check with regex
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,32}$/
if( !password.match(regex) ) {
password = generatePassword();
}
return password;
}
console.log( generatePassword() );
答案 15 :(得分:1)
这是另一种基于Stephan Hoyer解决方案的方法
getRandomString (length) {
var chars = 'abcdefghkmnpqrstuvwxyz23456789';
return times(length, () => sample(chars)).join('');
}
答案 16 :(得分:1)
更短:
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('');
}
答案 17 :(得分:0)
const alpha = 'abcdefghijklmnopqrstuvwxyz';
const calpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const num = '1234567890';
const specials = ',.!@#$%^&*';
const options = [alpha, alpha, alpha, calpha, calpha, num, num, specials];
let opt, choose;
let pass = "";
for ( let i = 0; i < 8; i++ ) {
opt = Math.floor(Math.random() * options.length);
choose = Math.floor(Math.random() * (options[opt].length));
pass = pass + options[opt][choose];
options.splice(opt, 1);
}
console.log(pass);
长度 8 个字符
至少 1 个大写
至少 1 个号码
至少 1 个特殊字符
答案 18 :(得分:0)
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;
}
答案 19 :(得分:0)
使用密码生成密码的代码将具有一定的长度(默认为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
}
答案 20 :(得分:0)
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;
答案 21 :(得分:0)
一个简单的 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();
答案 22 :(得分:0)
我在此页面上看到很多示例都在使用Math.random。此方法没有加密强度高的随机值,因此不安全。相反,建议使用Math.random使用getRandomValues或您自己的算法。
您可以使用Passfather。这是一个使用加密强度很高的算法的程序包。我是该软件包的所有者,所以您可以提出一些问题。
答案 23 :(得分:0)
这是我想分享的快速而动态的现代解决方案
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
}
答案 24 :(得分:0)
此方法提供了更改密码大小和字符集的选项。
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
答案 25 :(得分:0)
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)。
答案 26 :(得分:0)
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
答案 27 :(得分:0)
这是一个免费的,可配置的Javascript类,可生成随机密码: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));
答案 28 :(得分:-2)
这是我找到的解决方案,如果您查看页面的源代码,还可以看到他们如何实现其示例:
https://www.404it.no/en/blog/javascript_random_password_generator
JavaScript随机密码生成器 发布时间:2015年1月6日 更新时间:2015年1月18日 作者:Per Kristian Haakonsen