tags:

views:

70

answers:

2

What would be the best approach to creating a 8 character random password containing a-z, A-Z and 0-9?

Absolutely no security issues, this is merely for prototyping, I just want data that looks realistic.

I was thinking a for (0 to 7) Math.random to produce ASCII codes and convert them to characters. Do you have any other suggestions?

+4  A: 

I would probably use something like this:

function generatePassword() {
    var length = 8,
        charset = "abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
        retVal = "";
    for (var i = 0, n = charset.length; i < length; ++i) {
        retVal += charset.charAt(Math.floor(Math.random() * n));
    }
    return retVal;
}

That can then be extended to have the length and charset passed by a parameter.

Gumbo
Should probably be `Math.random() * n`. Other than that, works perfectly, and as you said, is easily modifiable. Thanks (:
peirix
@peirix: You’re right, `Math.random` does only return values of 0..1.
Gumbo
PS! The `floor` isn't needed. In this case, it will make `9` unobtainable.
peirix
@peirix: No, using `Math.floor` doesn’t make any difference.
Gumbo
A: 

Gumbo's solution does not work. This one does though:

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;

}
code_burgar
Gumbo's solution worked perfectly. I was able to get random characters between `a` and `9`...I'm guessing charAt will automatically `floor` or `round` the floating number.
peirix
it didn't work when copy pasted and ran, the concept is alright though
code_burgar
I'm guessing it didn't work because his first version was dividing by n, instead of multiplying it.
peirix