I am working on a JS function for generating password strings, it takes four parameters for a-z lowercase, A-Z uppercase, 0-9 and punctuations. I put together a base string, like this:
function genpwd(azlc,azuc,num,pun,len) {
var chars = "";
if (azlc) chars += "abcdefghijklmnopqrstuvwxyz";
if (azuc) chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (num) chars += "012345678901234567890123";
if (pun) chars += "!@#%&()=?+-_.:,;*{}[]^$/";
Then I loop through the base string (given length of the password) and randomly picking out chars to a new string and returns this as the output password.
for(i=0;i<len;i++) {
nextChar = chars.charAt(Math.floor(Math.random()*charsN));
password += nextChar;
}
return password;
}
This is a really simple way of generating a random string, but it does not guarantee that at least one char from each "char group" actually is included in the output string.
I have looked at some other examples on how to use regexps, but can't figure out how to modify them to work the way I want. I'm thinking the "easiest" way to solve this is probably by using a regexp - something like this:
if (password.magic_regexp_stuff) {
return password;
} else {
password = genpwd(azlc,azuc,num,pun,len);
}
- Am I on the right track?
- Can anyone help me with the regexp?
UPDATE:
Ok, so after some valuable input from all of you, I ended up with this function.
I also switched from mVChr suggestion (thanks man!) to the one posted by Py, so I'm pretty sure the "statistics problem" (don't have any other word for it) pointed out by NobRuked won't be a problem any more. Can someone confirm this please? :)
I also had to modify the function's parameters and approach to the sets of chars to be used. Any suggestions on improvements?
function passwd(len, azlc, azuc, num, pun) {
var len = parseInt(len),
ar = [],
checker = [],
passwd = '',
good = true,
num, num2,
sets = 0;
if(!len || len < 4) len = 12;
if(!azlc && !azuc && !num && !pun) { azlc = 1; azuc = 1; num = 1; pun = 1; }
if (azlc) {
ar.push("abcdefghijklmnopqrstuvwxyz");
checker.push(0);
sets++;
}
if (azuc) {
ar.push("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
checker.push(0);
sets++;
}
if (num) {
ar.push("0123456789");
checker.push(0);
sets++;
}
if (pun) {
ar.push("!@#%&()=?+-_.:,;*{}[]^$/");
checker.push(0);
sets++;
}
for (var i=0;i<len;i++){
num=rand(0,sets);
num2=rand(0,ar[num].length);
passwd+=ar[num][num2];
checker[num]=1;
}
for (var i=0;i<sets;i++){
if(checker[i]===0)
good=false;
}
if (good){
return passwd;
}
else{
return passwd(len);
}
}
Many thanks to everyone for your help, it's appreciated!