PDA

View Full Version : password generator code



micklep
12-18-2006, 09:27 PM
1) CODE TITLE: pissedandhappy password gen

2) AUTHOR NAME/NOTES: Peter

3) DESCRIPTION: this code complicated java code produces a number of random passwords, i currently can not find a good use for it but i think that it will be good for some sort of user database. Please tell me if you do use this code by emailing me at micklep@hotmail.com

4) URL TO CODE: http://www.stuff.pissedandhappy.co.uk/password-gen.txt

djr33
12-18-2006, 10:58 PM
It's javascript, so implementation in a database would be impossible, without recoding to php, asp, etc.

I'm confused by the various scripts... why is it setup in so many seperate <script></script> elements? Seems like needless extra stuff to me.

Really, you've just kinda randomly assigned things, but you could create a real random script by using the ordinal values for characters (0-9,a-z,A-Z, and symbols, etc. if you wanted) and choosing one at random.

Here's the PHP--

<?php
$len = 8; //set pass length //in this case, 8
for ($n=0;$n<$len;$n++) { //loop starting at 0, while less than len value
$ord = rand(1,62); //10num+26LET+26let //add more if you want
if ($ord <= 10) {$ord += 47;} //numbers
else if ($ord <= 36) {$ord += 54;} //LETTERS
else { $ord += 60; } //letters
//include other sets of chars if you want
$pass .= chr($ord); //add char to existing password
}
echo $pass; //output password
?>

Untested, but should work just fine.

If we were to compare the outputs, they would differ in complexity and randomness. Since you are using a much more limited set of characters, the inclusive code above would generate many more possible outcomes. Yours can work too, but this just has more possibilities.
I don't do JS, but I'm sure there's a way to do this as well.
You could just output as html, and use &#nn; for example.


EDIT: Consider this a submission if it seems worthy.


EDIT AGAIN: Ok, code fixed above...

djr33
12-19-2006, 08:13 AM
http://ci-pro.com/misc/phptest/passgen.php
That's a test page.

I had an error in the script earlier, but it's fixed now.
I was adding the full value for each set, like 64 for capital letters, but then realized that to be wrong since that set of random values starts at 10, so needed to subtract that first. For the next, subtract 10+26, so not 96, but 60.

shachi
12-20-2006, 05:17 PM
Great drj33!!! 10/10

djr33
12-21-2006, 01:30 AM
Hmm.... here's a more logical way to look at the code:
<?php
$len = 8; //set pass length //in this case, 8
for ($n=0;$n<$len;$n++) { //loop starting at 0, while less than len value
$ord = rand(1,62); //10num+26LET+26let //add more if you want
if ($ord <= 10) {
$ord += 47; //numbers
}
else {
$ord -= 10;
if ($ord <= 26) {
$ord += 64; //LETTERS
}
else {
$ord -= 26;
$ord += 96; //letters
}
}
//include other sets of chars if you want
$pass .= chr($ord); //add char to existing password
}
echo $pass; //output password
?>

The math was weird, and it confused me, so it's bound to confuse others, considering I wrote the script in the first place.


Hmm.... I might write that into an array/foreach function so you an specify character sets within the array (which would, interestingly enough, be a 3D array ;))

micklep
12-21-2006, 01:13 PM
in answer to your second post, the reason i did it in so many seperate script is because i was brand new to javascript.

Thanks to you i now know that i can put them all together in 1 set of code. I have produced another script that i think is rather fun:

DONT LOOK IF EASILY OFFENDED:

http://www.stuff.pissedandhappy.co.uk/insult.html

Tell me what you think, i added some html to spruce it up a bit but it seems to really affect loading time :(

Cheers

Twey
12-21-2006, 04:38 PM
Haha, er, interesting :p

djr33
12-22-2006, 02:36 AM
Hmmmm.... different. :)

exed
01-06-2007, 01:35 PM
my variant is


<?
function exPassGen( $passlen = 8 )
{
$lets = array(
0 => range('a', 'z'),
1 => range('A', 'Z'),
2 => range('0', '9'),
3 => array('~', '!', '#', '@', '$', '^', ':', '(', ')', '-', '_', '+', '='),
);
$ret = '';

for( $i = 0; $i < $passlen; $i++ )
{
$lrnd = rand(0, count($lets)-1 );
$ret .= $lets[$lrnd][ rand(0,count($lets[$lrnd])-1) ];
}

return $ret;
}

echo exPassGen( 10 )."<br/>";
echo exPassGen( 5 );
?>

djr33
01-06-2007, 10:15 PM
Hmm.... perhaps. But most of those symbols aren't valid as passwords, if you actually want to use that. You could use up to 255 characters, but many wouldn't work. Depends on the exact system, though.

Also, using the ascii codes really makes sense in this case, since it can be changed fairly easily. But doing it like that could work as well.

Do you have a test page?

jscheuer1
01-07-2007, 07:34 AM
Due to concerns about demands upon the server, javascript is often preferred as the first method (when available) to be used, with server side code waiting in the wings as a backup should the user not have javascript enabled. Once javascript has delivered the data to a form element, the server should be able to pick it up from there and stick it in the database. With that in mind and my seeing that the code originally presented here looked way too involved, I've come up with a shorter javascript method for generating passwords:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title>Password Gen - Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function random_pass(len){
var tokens=[];
for (var j = 0; j < len; j++){
tokens[tokens.length]=String.fromCharCode(parseInt((Math.floor(Math.random()*26)+65).toString(16),16));
tokens[tokens.length]=String.fromCharCode(parseInt((Math.floor(Math.random()*26)+97).toString(16),16));
tokens[tokens.length]=Math.floor(Math.random()*10)
}
tokens.sort(function() {return 0.5 - Math.random();}) //thanks to Mike (aka Mwinter) :)
tokens.length=len;
return tokens.join('');
}
</script>
</head>
<body>
<input type="text" size="9" id="pass" readonly style="font-family:serif;font-size:120%;">
<input type="button" value="Gen" onclick="document.getElementById('pass').value=random_pass(7);">
<input type="button" value="select" onclick="document.getElementById('pass').select();">
</body>
</html>

Notes: Generates passwords consisting only of letters (upper and lower case) and numbers.

Usage of the function is:

random_pass(length)

where length is the desired number of characters in the password. The code could probably be simplified further but, you will note that it generates on the order of three times as many characters as will be required and then randomizes those before choosing the finished password. I think this makes for a robustly random password. What could probably be simplified most is the generation of the upper and lower case letters, I'm just not sure how.

exed
01-07-2007, 12:10 PM
Also, using the ascii codes really makes sense in this case, since it can be changed fairly easily. But doing it like that could work as well.

Do you have a test page?

I update script, it's working correctly.

test page:
http://ligr.info/_tools/passgen.php?passlen=400

passlen=xxx - option for length test


jscheuer1, very, very good script.
I could not find this function String.fromCharCode.
Thank you!

Twey
01-07-2007, 12:44 PM
Javascript:
function PasswordGenerator(defaultLength) {
var i;

this.length = defaultLength || 8;
this.data = [];
this.weighted = [];

for(i = 0x20; i < 0x7F; ++i)
this.data.push(
{
'weight' : 1,
'datum' : String.fromCharCode(i)
}
);

this.recalcWeights();
}

PasswordGenerator.prototype.setLength = function(length) {
var l;
if(!isNaN(l = parseInt(length)))
return (this.length = length);
else return this.length;
};

PasswordGenerator.prototype.clearData = function() {
this.data = [];
this.recalcWeights();
};

PasswordGenerator.prototype.findDatum = function(datum) {
for(var i = 0; i < this.data.length; ++i)
if(this.data[i].datum === datum)
return i;
return -1;
};

PasswordGenerator.prototype.addData = function(data, weight) {
var weight = parseInt(weight, 10);
if(isNaN(weight))
weight = 1;
for(var i = 0, c; !isNaN((c = data.charAt(i)).charCodeAt(0)); ++i)
this.addDatum(c, weight);
};

PasswordGenerator.prototype.addDatum = function(datum, weight) {
var weight = parseInt(weight, 10);
if(isNaN(weight))
weight = 1;

if(this.findDatum(datum) !== -1)
this.removeDatum(datum);

this.data.push({'datum' : datum, 'weight' : weight});
this.recalcWeights();
};

PasswordGenerator.prototype.removeDatum = function(datum) {
var index = this.findDatum(datum);
if(index === -1)
return null;
this.data.splice(index, 1);
this.recalcWeights();
};

PasswordGenerator.prototype.recalcWeights = function() {
for(var i = 0; i < this.data.length; ++i)
for(var j = 0; j < this.data[i].weight; ++j)
this.weighted.push(this.data[i].datum);
};

PasswordGenerator.prototype.getCharacter = function() {
return this.weighted[Math.floor(Math.random() * this.weighted.length)];
};

PasswordGenerator.prototype.generate = function() {
var ret = "";
for(var i = 0; i < this.length; ++i)
ret += this.getCharacter();
return ret;
};Or PHP:
class PasswordGenerator {
var $length;
var $data;
var $weighted;

function PasswordGenerator($defaultLength = 8) {
$this->length = $defaultLength;
$this->data = array();
$this->weighted = array();

for($i = 0x20; $i < 0x7F; ++$i)
array_push($this->data, array('weight' => 1, 'datum' => chr($i)));

$this->recalcWeights();
}

function setLength($length = 0) {
if($length < 1) return $this->length;
return $this->length;
}

function clearData() {
$this->data = array();
$this->recalcWeights();
}

function findDatum($datum) {
foreach($this->data as $key => $val)
if($val === $datum)
return $key;
return -1;
}

function addData($data, $weight = 1) {
$c;
for($i = 0; (ord($c = $data[$i])); ++$i)
$this->addDatum($c, $weight);
}

function addDatum($datum, $weight = 1) {
if($this->findDatum($datum) !== -1)
$this->removeDatum($datum);
array_push($this->data, array('datum' => $datum, 'weight' => $weight));
$this->recalcWeights();
}

function removeDatum($datum) {
$index = $this->findDatum($datum);
if($index === -1)
return null;
array_splice($this->data, $index, 1);
$this->recalcWeights();
}

function recalcWeights() {
foreach($this->data as $key => $val)
for($j = 0; $j < $val['weight']; ++$j)
array_push($this->weighted, $val['datum']);
}

function getCharacter() {
return $this->weighted[rand(0, count($this->weighted) - 1)];
}

function generate() {
$ret = "";
for($i = 0; $i < $this->length; ++$i)
$ret .= $this->getCharacter();
return $ret;
}
}Tested slightly but not extensively.

jscheuer1
01-08-2007, 07:53 AM
Thanks, Twey. I knew that finding the alphabet characters could be simplified. The function is now very short and sweet and defaults to a 7 character password (usage is the same as before):


function random_pass(l){
var t='', l=l||7, c=function(hx){return String.fromCharCode(Math.floor(Math.random()*0x1a)+hx);};
for (var j=0, g=Math.floor(Math.random()*3); j<l; j++, g=Math.floor(Math.random()*3))
t+=g>1? c(0x41) : g? c(0x61) : Math.floor(Math.random()*10);
return t;
}

The page is a little more complex owing to style used to make the output clearer:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title>Password Gen - Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
#pass {
font-family:serif;
font-size:120%;
letter-spacing:2px;
}
</style>
<script type="text/javascript">
function random_pass(l){
var t='', l=l||7, c=function(hx){return String.fromCharCode(Math.floor(Math.random()*0x1a)+hx);};
for (var j=0, g=Math.floor(Math.random()*3); j<l; j++, g=Math.floor(Math.random()*3))
t+=g>1? c(0x41) : g? c(0x61) : Math.floor(Math.random()*10);
return t;
}
</script>
</head>
<body>
<input id="pass" type="text" readonly size="9">
<input type="button" value="Gen" onclick="document.getElementById('pass').value=random_pass();">
<input type="button" value="select" onclick="document.getElementById('pass').select();">
</body>
</html>