473,503 Members | 241 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generating random password strings in JavaScript

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
14 4708
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
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
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
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
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
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
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
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
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
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
>
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
23093
by: Andreas Lobinger | last post by:
Aloha, i wanted to ask another problem, but as i started to build an example... How to generate (memory and time)-efficient a string containing random characters? I have never worked with...
7
7245
by: eric.gagnon | last post by:
In a program randomly generating 10 000 000 alphanumeric codes of 16 characters in length (Ex.: "ZAZAZAZAZAZAZ156"), what would be an efficient way to ensure that I do not generate duplicates? ...
2
1474
by: Joe | last post by:
Hi, I am building web in ASP.NET using VB.NET to code the pages. I want to generate random passwords for users. I know that password hashing is built right into the .NET Framework. I was...
2
2757
by: Simon Wittber | last post by:
I'm building a web application using sqlalchemy in my db layer. Some of the tables require single integer primary keys which might be exposed in some parts of the web interface. If users can...
3
2068
by: tshad | last post by:
I have a page that I am getting a username and password as a random number (2 letters, one number and 4 more letters) I have 2 functions I call: *************************************************...
2
1959
by: RYAN1214 | last post by:
How can I use this random password code, and then insert the password into email which is sent to the user after the registration has been finished? thx <html> <head> <title>Javascript:...
3
6733
by: John | last post by:
Hi How can I generate a random password of 8 characters (digits and letters) in vb? Thanks Regards
6
1795
by: Mike P | last post by:
I am generating 12 random strings and my code works fine when I step through, but when I then let it run without stepping through and populate a listbox with the array I am building, I get the same...
1
2026
by: Krimp | last post by:
I pulled this code from Vbasic.net or generating random passwords. I want to know how I can set up so that each time the page is refreshed a new password is generated without having to fill in the...
0
7203
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7282
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6995
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5581
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5017
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4678
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3157
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1515
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
738
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.