Generating random password strings in JavaScript

A

avanti

Hi,

I need to generate random alphanumeric password strings for the users
in my application using Javascript. Are there any links that will have
pointers on the same?

Thanks,
Avanti
 
J

Jim

Avanti,
You can create 2 functions that will return random letters and numbers,
and then one primary function which will create the final password:

<script type="text/javascript" >
function createPassword(){
var char1 = returnAlpha();
var char2 = returnAlpha();
var char3 = returnAlpha();
var char4 = returnAlpha();
var num1 = returnInt();
var num2 = returnInt();
var num3 = returnInt();
var num4 = returnInt();
var num5 = returnInt();
var password = char1 + char2 + num5 + num4 + char3 + num3 + num2 +
num1 + char4;
alert(password);
}

function returnInt(){
var numb =Math.floor(Math.random()*9);
return numb;
}

function returnAlpha(){
var alpha = new
Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
var alpha_index =Math.floor(Math.random()*26);
return alpha[alpha_index];
}
</script>
</head>
<body >
<button onClick = "createPassword()">Create Password</button>
</body>
 
R

RobG

avanti said:
Hi,

I need to generate random alphanumeric password strings for the users
in my application using Javascript. Are there any links that will have
pointers on the same?

Depending on the characters you want and how many, modify the
following:

<script type="text/javascript">

function genPassword(len){
var chars = 'abcdefghijklmnopqrstuvwxyz0123456789'.split('');
var i = chars.length;
var pwd = [];
while(len--){
pwd[len] = chars[Math.random()*i | 0];
}
return pwd.join('');
}

</script>
<button onclick="alert(genPassword(8));">Get password</button>
 
C

Chad Burggraf

avanti said:
Hi,

I need to generate random alphanumeric password strings for the users
in my application using Javascript. Are there any links that will have
pointers on the same?

Thanks,
Avanti

Below is a script I wrote a while ago which generates random
alphanumeric strings. The concept is widely used and definitely not
novel to this code. Warning: It uses the Prototype.js class construct.
You could easily rewrite it to avoid that though.

//
// Generates random alphanumeric strings.
//
Generator = Class.create();
Generator.prototype = {

// Properties.
aConsLow:['b','c','d','f','g','h','j','k','l',
'm','n','p','q','r','s','t','v','w','x','y','z'],
aConsUp:['B','C','D','F','G','H','J','K','L',
'M','N','P','Q','R','S','T','V','W','X','Y','Z'],
aHardConsLow:['b','c','d','f','g','h',
'k','m','p','s','t','v','z'],
aHardConsUp:['B','C','D','F','G','H',
'K','M','P','S','T','V','Z'],
aLinkConsLow:['h','l','r'],
aLinkConsUp:['H','L','R'],
aVowelsLow:['a','e','i','o','u'],
aVowelsUp:['A','E','I','U'],
aDigits:['1','2','3','4','5','6','7','8','9'],

// Constructor.
initialize:function() {
this.CallRandom(new Date().getSeconds());
this.aFormat = [this.aConsLow, this.aConsUp, this.aDigits,
this.aHardConsLow, this.aHardConsUp, this.aDigits,
this.aLinkConsLow, this.aLinkConsUp, this.aDigits,
this.aVowelsLow, this.aVowelsUp, this.aDigits];
},

// Calls Math.random() the given number of times and returns the
// result of the last call.
CallRandom:function(iCount) {
while(iCount - 1 > 0) {
Math.random();
--iCount;
}

return Math.random();
},

// Gets a random index in aFrom.
GetRandomIndex:function(aFrom) {
return Math.floor(this.CallRandom(new Date().getSeconds()) *
aFrom.length);
},

// Gets a random item in aFrom.
GetRandomItem:function(aFrom) {
return aFrom[this.GetRandomIndex(aFrom)];
},

// Generates and returns a password of the given length;
Generate:function(iLength) {
var sPw = "";
while(iLength > 0) {
sPw += this.GetRandomItem(
this.aFormat[
this.GetRandomIndex(this.aFormat)
]
);
--iLength;
}
return sPw;
}
};

Cheers!
Chad
 
R

RobG

Chad said:
Below is a script I wrote a while ago which generates random
alphanumeric strings. The concept is widely used and definitely not
novel to this code. Warning: It uses the Prototype.js class construct.
You could easily rewrite it to avoid that though.

Yes, change:

Generator = Class.create();

to:

function Generator(){};

I can't see the point of using Prototype.js when you haven't used any
of the extra bits it adds to its "Class" objects. Using an object as a
class this way is normally indicated if you intend to create a number
of them to operate simultaneously, usually with some degree of
independence: I don't see the need in this case.

[...]
aLinkConsLow:['h','l','r'],
aLinkConsUp:['H','L','R'],

Why give these particular characters twice the probability of being
selected as the others?


[...]
aDigits:['1','2','3','4','5','6','7','8','9'],

Why doesn't zero get a guernsey? If you've removed it to prevent
confusion with upper-case O, then you need to remove O too.

I get the feeling that you were going to generate strings with
restrictions on the characters, such as only consonants or vowels, but
didn't post the code. Otherwise, there is no point to all those arrays
that are concatenated into one.

// Constructor.
initialize:function() {
this.CallRandom(new Date().getSeconds());

Calling CallRandom() here appears to serve no useful purpose - the
result isn't saved and it doesn't initialise anything.
this.aFormat = [this.aConsLow, this.aConsUp, this.aDigits,
this.aHardConsLow, this.aHardConsUp, this.aDigits,
this.aLinkConsLow, this.aLinkConsUp, this.aDigits,
this.aVowelsLow, this.aVowelsUp, this.aDigits];
},

// Calls Math.random() the given number of times and returns the
// result of the last call.

Is there an issue with the built-in Math.random function? Do you have
evidence that calling it up to 59 times results in a "more random"
number than if it is only called once? It certainly takes (much)
longer. Given that the function runs in less than a few milliseconds,
it will nearly always be called with the same value for 'iCount' each
time.

If run toward the end of a minute, it may take 10 times longer (or
more) to run than if called at the start of a minute.

CallRandom:function(iCount) {
while(iCount - 1 > 0) {
Math.random();
--iCount;
}

More concisely:

while(Count--){ Math.random(); }

Not withstanding the apparent futility of doing so.

return Math.random();
},
[...]

Remove the dependency on Prototype.js and you save your users a 64kb
download. Remove the pointless CallRandom function and it will run up
to 15 times faster. But hey, if it works for you. ;-)
 
B

Bart Van der Donck

Chad said:
[...]
//
// Generates random alphanumeric strings.
//
Generator = Class.create();
Generator.prototype = {

// Properties.
aConsLow:['b','c','d','f','g','h','j','k','l',
'm','n','p','q','r','s','t','v','w','x','y','z'],
aConsUp:['B','C','D','F','G','H','J','K','L',
'M','N','P','Q','R','S','T','V','W','X','Y','Z'],
aHardConsLow:['b','c','d','f','g','h',
'k','m','p','s','t','v','z'],
aHardConsUp:['B','C','D','F','G','H',
'K','M','P','S','T','V','Z'],
aLinkConsLow:['h','l','r'],
aLinkConsUp:['H','L','R'],
aVowelsLow:['a','e','i','o','u'],
aVowelsUp:['A','E','I','U'],
aDigits:['1','2','3','4','5','6','7','8','9'],

// Constructor.
initialize:function() {
this.CallRandom(new Date().getSeconds());
this.aFormat = [this.aConsLow, this.aConsUp, this.aDigits,
this.aHardConsLow, this.aHardConsUp, this.aDigits,
this.aLinkConsLow, this.aLinkConsUp, this.aDigits,
this.aVowelsLow, this.aVowelsUp, this.aDigits];
},

// Calls Math.random() the given number of times and returns the
// result of the last call.
CallRandom:function(iCount) {
while(iCount - 1 > 0) {
Math.random();
--iCount;
}

return Math.random();
},

// Gets a random index in aFrom.
GetRandomIndex:function(aFrom) {
return Math.floor(this.CallRandom(new Date().getSeconds()) *
aFrom.length);
},

// Gets a random item in aFrom.
GetRandomItem:function(aFrom) {
return aFrom[this.GetRandomIndex(aFrom)];
},

// Generates and returns a password of the given length;
Generate:function(iLength) {
var sPw = "";
while(iLength > 0) {
sPw += this.GetRandomItem(
this.aFormat[
this.GetRandomIndex(this.aFormat)
]
);
--iLength;
}
return sPw;
}
};

As a side remark, I would avoid characters like these in passwords for
users:

0 vs O (zero vs capital O)
1 vs l vs I (integer one vs lower case L vs capital i)
 
Z

zero0x

it isnt very good idea to generate random password in javascript,
because it is very unsafe. you'd better use server-side scripting to
generate random passwords.

this book http://innocentcode.thathost.com/ describes, how can it be
exploited, i have got it, and it is great.
avanti napísal(a):
 
B

Bart Van der Donck

zero0x said:
it isnt very good idea to generate random password in javascript,
because it is very unsafe. you'd better use server-side scripting to
generate random passwords.

Supposed that the password is shown on the user's screen, then the act
of generating a random password is just as safe when doing it client-
or serverside. In a strict sense, clientside would even be more secure
here, because the traffic cannot be eavesdropped.

What happens next is a different story of course (store passwords,
actual authentication script, admin password management, encryption,
etc.)
this book http://innocentcode.thathost.com/ describes, how can it be
exploited, i have got it, and it is great.

Well I don't have the book. Mind to share that exploit ?
 
C

Chad Burggraf

RobG said:
I can't see the point of using Prototype.js when you haven't used any
of the extra bits it adds to its "Class" objects. Using an object as a
class this way is normally indicated if you intend to create a number
of them to operate simultaneously, usually with some degree of
independence: I don't see the need in this case.

I agree. The class was written along with a lot of others for a project
in which I was using Prototype.js. It was simply written this way for
clarity and consistency.
Why doesn't zero get a guernsey? If you've removed it to prevent
confusion with upper-case O, then you need to remove O too.

I figured that it would be okay to assume O. You're probably right
though, although it wasn't of particular importance for the specific
application.
I get the feeling that you were going to generate strings with
restrictions on the characters, such as only consonants or vowels, but
didn't post the code. Otherwise, there is no point to all those arrays
that are concatenated into one.

You're right again.
Is there an issue with the built-in Math.random function? Do you have
evidence that calling it up to 59 times results in a "more random"
number than if it is only called once? It certainly takes (much)
longer. Given that the function runs in less than a few milliseconds,
it will nearly always be called with the same value for 'iCount' each
time.

Actually, I simply didn't know how it was being seeded. The slowness
factor is practically irrelevant though as it runs virtually
instantaneously as is. I was trying to get to a somewhat random point in
the sequence each time. Playing with it in FF it appears that
Math.random() is using a time-based seed so CallRandom() is pointless.
More concisely:

while(Count--){ Math.random(); }

Now you're just nit-picking.
Remove the dependency on Prototype.js and you save your users a 64kb
download. Remove the pointless CallRandom function and it will run up
to 15 times faster. But hey, if it works for you. ;-)

Prototype.js would be trivial to remove from this class, so if you don't
use it elsewhere in your application then by all means go for it.

If anyone has any more information on how Math.random() works I would be
very interested. How is it being seeded? When is it being seeded? What
algorithm is used?

Cheers
Chad
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
function returnInt(){
var numb =Math.floor(Math.random()*9);
return numb;


That will never (except in buggy Opera and any similar) return 9.

See FAQ 4.22, ignoring the bit about N>2.

It's a good idea to read the newsgroup and its FAQ. See below.
 
D

Dr J R Stockton

Mon said:
If anyone has any more information on how Math.random() works I would
be very interested. How is it being seeded? When is it being seeded?
What algorithm is used?

See the appropriate section of ECMA-262 (via FAQ, I presume), which is
15.8.2.14. By specification, the exact behaviour is unspecified.

Math.random() returns a Number X such that 0<=X<1, with 53 bits of float
resolution.

It can be shown that some browsers have an internal RNG with 32-bit
resolution; I've heard of nothing lower. My browser gives the full 53
bits. It seems likely that the internal RNG of better browsers is
64-bit, but I've only just thought about how to test that.

I have code for an initialisable, repeatable 32-bit JS RNG matching that
of Borland's Pascal/Delphi, and the constants (in Knuth) for a 64-bit
generator. I seek constants for a good 48-bit generator.

Constants apart, I expect the RNG to use R[n] = (a * R[n-1] + b ) % c
where c is 2^k, k is 32 48 53 or 64, and b is probably 1. AFAICS,
nothing can be simpler; and AFAIK that's good enough for general use.

I don't know how the RNG, if of over 53 bits, is mapped onto Number;
there are at least two possible ways.

It's a good idea to read the newsgroup and its FAQ. See below, and
<URL:http://www.merlyn.demon.co.uk/js-randm.htm>.
 
Z

zero0x

Well I don't have the book. Mind to share that exploit ?

it describes widely how can it be exploited, when you are doing some
important tasks in javascript (client-side scripting) instead of server
scripting..

looks like this one is not so important
 
C

Chad Burggraf

Dr said:
It can be shown that some browsers have an internal RNG with 32-bit
resolution; I've heard of nothing lower. My browser gives the full 53
bits. It seems likely that the internal RNG of better browsers is
64-bit, but I've only just thought about how to test that.

Would you mind sharing?
I have code for an initialisable, repeatable 32-bit JS RNG matching that
of Borland's Pascal/Delphi, and the constants (in Knuth) for a 64-bit
generator. I seek constants for a good 48-bit generator.

Again, would you mind sharing?
Constants apart, I expect the RNG to use R[n] = (a * R[n-1] + b ) % c
where c is 2^k, k is 32 48 53 or 64, and b is probably 1. AFAICS,
nothing can be simpler; and AFAIK that's good enough for general use.

I don't know how the RNG, if of over 53 bits, is mapped onto Number;
there are at least two possible ways.

It's a good idea to read the newsgroup and its FAQ. See below, and
<URL:http://www.merlyn.demon.co.uk/js-randm.htm>.

Thank you for your great insight. I actually found this group via your
Web page on Javascript dates, which I found both intriguing and helpful.

Cheers
Chad
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]>,
Would you mind sharing?

No. But "thought about" != "solved". The current code is function
Resol2 in my js-randm.htm; but, as it didn't show anything useful (in
IE6) in millions of Math.random(), it is currently neither displayed nor
executed. Further thought might occur, buy do try yourself.

Again, would you mind sharing?

No. "Repeatable Random Numbers", js-randm.htm#RR , and the link to my
pas-rand.htm .
 
C

Chad Burggraf

Dr said:
No. But "thought about" != "solved". The current code is function
Resol2 in my js-randm.htm; but, as it didn't show anything useful (in
IE6) in millions of Math.random(), it is currently neither displayed nor
executed. Further thought might occur, buy do try yourself.
No. "Repeatable Random Numbers", js-randm.htm#RR , and the link to my
pas-rand.htm .

Thank you very much, I will definitely check these out.

Cheers
Chad
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top