473,748 Members | 2,567 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 4750
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(Mat h.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(Mat h.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 = 'abcdefghijklmn opqrstuvwxyz012 3456789'.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.proto type = {

// 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:func tion() {
this.CallRandom (new Date().getSecon ds());
this.aFormat = [this.aConsLow, this.aConsUp, this.aDigits,
this.aHardConsL ow, this.aHardConsU p, this.aDigits,
this.aLinkConsL ow, this.aLinkConsU p, 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:func tion(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().getSecon ds()) *
aFrom.length);
},

// Gets a random item in aFrom.
GetRandomItem:f unction(aFrom) {
return aFrom[this.GetRandomI ndex(aFrom)];
},

// Generates and returns a password of the given length;
Generate:functi on(iLength) {
var sPw = "";
while(iLength 0) {
sPw += this.GetRandomI tem(
this.aFormat[
this.GetRandomI ndex(this.aForm at)
]
);
--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:func tion() {
this.CallRandom (new Date().getSecon ds());
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.aHardConsL ow, this.aHardConsU p, this.aDigits,
this.aLinkConsL ow, this.aLinkConsU p, 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:func tion(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.proto type = {

// 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:func tion() {
this.CallRandom (new Date().getSecon ds());
this.aFormat = [this.aConsLow, this.aConsUp, this.aDigits,
this.aHardConsL ow, this.aHardConsU p, this.aDigits,
this.aLinkConsL ow, this.aLinkConsU p, 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:func tion(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().getSecon ds()) *
aFrom.length);
},

// Gets a random item in aFrom.
GetRandomItem:f unction(aFrom) {
return aFrom[this.GetRandomI ndex(aFrom)];
},

// Generates and returns a password of the given length;
Generate:functi on(iLength) {
var sPw = "";
while(iLength 0) {
sPw += this.GetRandomI tem(
this.aFormat[
this.GetRandomI ndex(this.aForm at)
]
);
--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.javas cript message <11************ **********@s34g 2000cwa.go
oglegroups.com> , Sun, 31 Dec 2006 21:28:57, Jim <ji*******@aol. com>
posted:
>function returnInt(){
var numb =Math.floor(Mat h.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.c om/faq/index.html>.
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Jan 1 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
23165
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 generators, so my solution at the moment is: import string import random random.seed(14)
7
7287
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? STL set, map? Could you give me a little code example? Thank you.
2
1494
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 wondering if there is any built-in support for generating random passwords in .Net. If the support is built-in, can you show me how to do it. Thanks, Joe
2
2775
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 guess the next key in a sequence, it might be possible for them to 'game' or manipulate the system in unexpected ways. I want to avoid this by generating a random key for each row ID, and have decided to use the same approach for all my single key...
3
2082
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: ************************************************* Function RandomString(size as integer, lowerCase as boolean) as string Dim builder as StringBuilder = new StringBuilder() Dim random as Random = new Random() Dim i as integer dim ch as char
2
1972
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: Password Generator</title> <style type="text/css"> input, select { font-family: Verdana, Arial, sans-serif;
3
6742
by: John | last post by:
Hi How can I generate a random password of 8 characters (digits and letters) in vb? Thanks Regards
6
1813
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 value repeated 12 times. Here is my code : protected void btnGenerate_Click(object sender, EventArgs e) { string strDomainName = txtDomainName.Text.ToString(); string strEmailAddress = ""; string strEmailAddressComplete = "";
1
2035
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 form boxes. Anyone lend a hand? http://vbasic.net/detail.aspx?tid=105 Code: <form id="form1" runat="server"> <div> Enter Required Password Length: <asp:TextBox ID="TextBox1" runat="server" Columns="2" MaxLength="2"></asp:TextBox><br />...
0
9386
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9333
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6799
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6078
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3319
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 we have to send another system
2
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2217
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.