Page 2 of 2 FirstFirst 12
Results 11 to 14 of 14

Thread: password generator code

  1. #11
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    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:

    Code:
    <!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.
    Last edited by jscheuer1; 01-07-2007 at 10:19 AM. Reason: simplify code & add style
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  2. #12
    Join Date
    Jan 2007
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question

    Quote Originally Posted by djr33 View Post
    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!
    Last edited by exed; 01-07-2007 at 01:22 PM. Reason: add post

  3. #13
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Javascript:
    Code:
    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:
    Code:
    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.
    Last edited by Twey; 01-08-2007 at 05:17 AM.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  4. #14
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    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):

    Code:
    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:

    Code:
    <!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>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •