Jump to content

Javascript Password Generator.


madsovenielsen

Recommended Posts

Hello all.i want to make a random password generator, exclusively in JavaScript. but i have no idea how to do it.im thinking about looping through an array with a-z A-Z and 0-9. but really i have no clue.Any thoughts please./mads

Link to comment
Share on other sites

Start with generating a random number. You can use Math.random to do that, it will let you generate a number between any two numbers.Check the ASCII table:http://asciitable.com/The random number you want to generate should be between 48 and 123, so you would use Math.floor(Math.random(48, 123)) to generate a number. Then you need a series of if statements to check if the number is either between 48-57, or 65-90, or 97-122, which according to the ASCII table are the digits, then uppercase, then lowercase. If it is, then you convert the number to the corresponding ASCII character using String.fromCharCode. So if you do String.fromCharCode(77), you'll get the "M" character.So all of that is one loop. Each time through the loop you generate a random number between 48 and 123, check if it's in one of the three ranges, and add it to the string if it is. If it's not, you just generate another number and check again. You keep looping until the length of the string reaches the password length you're trying to get to. You can look over the ASCII table and see if there are other characters you want to add as well. Don't use any characters below 32, they aren't printable, don't use 127 either. You may also want to eliminate 0, O, 1, I, and l from the passwords to avoid confusion.

Link to comment
Share on other sites

Hey. the Math.floor(Math.random(48, 123)) dosent seem to work. im testing it like this.

function passwordgen() {var RndNum = Math.floor(Math.random(48, 123));document.getElementById("test").innerHTML = RndNum;}

what am i doing wrong ?/mads

Link to comment
Share on other sites

I don't think the random method takes arguments. Maybe try something like this.

function randomN() {var randomNumber = Math.floor(Math.random()*122+1);if (randomNumber >= 48 && randomNumber <= 123) { document.getElementById("test").innerHTML = randomNumber;} else { randomN()}}randomN();

Link to comment
Share on other sites

Ok i tried to make a random password generator in javascript, my code prints a string containing 10 chars with either capitals, lowercase letters or digits. Here it is:

<html><body><div id='test'></div><script>function randomN() {var randomNumber = Math.floor(Math.random()*122+1);if (randomNumber >= 48 && randomNumber <= 57 || randomNumber >= 65 && randomNumber <= 90 || randomNumber >= 97 && randomNumber <= 122) {document.getElementById("test").innerHTML += String.fromCharCode(randomNumber);} else {randomN()}}for (var i = 0; i < 10; i++) {	randomN();}</script></body></html>

Link to comment
Share on other sites

Just for the sake of learning, another approach would be to create a string of valid characters and then create a random number between 0 and the length of your string to get an index. Then use that index to return a specific character from your string. Do this how every many times you need to create a password that is the appropriate length.As an example, here's how you could use this method to create a random color hex code:

<html><body><script type="text/javascript">var chars = "0123456789ABCDEF";var hex = "";var rndIdx = 0;for(var i = 0; i < 6; i++){	rndIdx = Math.floor(Math.random()*chars.length);	hex+= chars.substr(rndIdx,1);}document.body.style.backgroundColor = "#" + hex;</script></body></html>

Link to comment
Share on other sites

I got curious about this anyway, so I did some benchmarking. The first step was to make the randomizing function return a character instead of printing a character. I concatenated the characters and printed the resulting string only after the benchmark.I ran the main test in Firefox (Mac)I didn't like the look of all the && and || operators, so I first tried a regex. Not much difference. I'm guessing that the bottleneck is the recursion that takes place when the test expression evaluates as false.jesh's method (expanded to include the full alphabet, uppercase and lower) is far superior, coming in at twice the speed.When I converted the master string to an array, the speed doubled again.I ran 50 trials of each method; each trial built a string of 10,000 characters.Trials in Safari and Opera showed the same trend, though the actual speeds were slower, and the differences greater.Platform and processor differences may yield different results.

Link to comment
Share on other sites

I don't think the random method takes arguments.
Correct, I was thinking PHP.I actually wasn't intending to use recursion like Vytas did, I was thinking something more like this:
function generate_password(len) {  var retval = "";  var randomNumber;    while (retval.length < len)  {	randomNumber = Math.floor((Math.random() * (123 - 48)) + 48);	if ((randomNumber >= 48 && randomNumber <= 57) || (randomNumber >= 65 && randomNumber <= 90) || (randomNumber >= 97 && randomNumber <= 122))	{	  retval += String.fromCharCode(randomNumber);	}  }    return retval;}

That should be faster than Vytas' original code, but it still won't be as fast as using a string or array because it's not necessarily going to loop the minimum number of times. If it does loop the minimum number of times it will only be slightly slower, but still a little slower because of the if statement.

Link to comment
Share on other sites

Yeah. My regex version used the while loop:

function randomReg () {	var r;	var c;	do  {		r = Math.floor((75 * Math.random() ) + 48);		c = String.fromCharCode(r);	}	while (c.match(/[^a-zA-Z0-9]/));	return c;}

This variation on jesh's suggestion works much faster:

chars = ['0','1','2','3','4','5','6','7','8','9', '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', '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'];function randomNew () {	var i = Math.floor(Math.random() * chars.length);	return chars[i];}

Which is no surprise, since there is no looping and two less internal functions. For anyone considering this, defining the chars array as a global is also important. If you're going to call randomNew() over and over, there is no sense initializing the same 62-member array over and over.Now, someone might be thinking that we could speed things up by writing it this way:

return chars[Math.floor(Math.random() * chars.length)];

Again, I'm accumulating the results of 50 trials of 10,000 calls (so 500,000 calls in all). In Firefox and Opera, I noticed no gain or loss. To my surprise, in Safari the speed was consistently 5% better.Then again, we're talking passwords. The real bottleneck will always be the HTTP request.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...