By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,058 Members | 1,209 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,058 IT Pros & Developers. It's quick & easy.

Generating random password strings in JavaScript

P: n/a
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

Jan 1 '07 #1
Share this Question
Share on Google+
14 Replies


P: n/a
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>

Jan 1 '07 #2

P: n/a
avanti wrote:
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>

--
Rob

Jan 1 '07 #3

P: n/a
avanti wrote:
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
Jan 1 '07 #4

P: n/a
Chad Burggraf wrote:
avanti wrote:
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.
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. ;-)
--
Rob

Jan 1 '07 #5

P: n/a
Chad Burggraf wrote:
[...]
//
// 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)

--
Bart

Jan 1 '07 #6

P: n/a
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):
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
Jan 1 '07 #7

P: n/a
zero0x wrote:
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 ?

--
Bart

Jan 1 '07 #8

P: n/a
RobG wrote:
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
Jan 1 '07 #9

P: n/a
In comp.lang.javascript message <11**********************@s34g2000cwa.go
oglegroups.com>, Sun, 31 Dec 2006 21:28:57, Jim <ji*******@aol.com>
posted:
>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.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 IE 6
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Jan 1 '07 #10

P: n/a
In comp.lang.javascript message <tr*****************@newsfe24.lga>, Mon,
1 Jan 2007 13:47:25, Chad Burggraf <ch***********@gmail.composted:
>
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>.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 IE 6
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Jan 2 '07 #11

P: n/a
>
Well I don't have the book. Mind to share that exploit ?

--
Bart
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

Jan 2 '07 #12

P: n/a
Dr J R Stockton wrote:
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
Jan 3 '07 #13

P: n/a
In comp.lang.javascript message <ps******************@newsfe23.lga>,
Tue, 2 Jan 2007 21:39:52, Chad Burggraf <ch***********@gmail.com>
posted:
>Dr J R Stockton wrote:
>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?
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.

>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?
No. "Repeatable Random Numbers", js-randm.htm#RR , and the link to my
pas-rand.htm .

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.merlyn.demon.co.uk/clpb-faq.txt RAH Prins : c.l.p.b mFAQ;
<URL:ftp://garbo.uwasa.fi/pc/link/tsfaqp.zipTimo Salmi's Turbo Pascal FAQ.
Jan 3 '07 #14

P: n/a
Dr J R Stockton wrote:
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
Jan 4 '07 #15

This discussion thread is closed

Replies have been disabled for this discussion.