Somewhat understandable random password generator





19
Date Submitted Mon. Oct. 9th, 2006 10:39 PM
Revision 1 of 1
Helper inxilpro
Tags "Random Generation" | Generator | Password | PHP | Random
Comments 2 comments
This function creates relatively secure random passwords. It's by no means ideal, but it should work in most non-critical situations. The nice thing is the generator attempts to create passwords that people can pronounce and chooses letters that won't be mistaken for others (such as the numeral "1", an upper-case "i" and a lower-case "L"). To keep the code short much of this functionality is very rudimentary, but it's better than nothing.

<?php
/**
 * Generates slightly more human-understandable random passwords
 *
 * @param int $len
 * @return string
 */

function makePassword($len = 8)
{
        $vowels = array('a', 'e', 'i', 'o', 'u', 'y');
        $confusing = array('I', 'l', '1', 'O', '0');
        $replacements = array('A', 'k', '3', 'U', '9');
        $choices = array(0 => rand(0, 1), 1 => rand(0, 1), 2 => rand(0, 2));
        $parts = array(0 => '', 1 => '', 2 => '');
       
        if ($choices[0]) $parts[0] = rand(1, rand(9,99));
        if ($choices[1]) $parts[2] = rand(1, rand(9,99));
       
        $len -= (strlen($parts[0]) + strlen($parts[2]));
        for ($i = 0; $i < $len; $i++)
        {
                if ($i % 2 == 0) $parts[1] .= chr(rand(97, 122));
                else $parts[1] .= $vowels[array_rand($vowels)];
        }
        if ($choices[2]) $parts[1] = ucfirst($parts[1]);
        if ($choices[2] == 2) $parts[1] = strrev($parts[1]);
       
        $r = $parts[0] . $parts[1] . $parts[2];
        $r = str_replace($confusing, $replacements, $r);
        return $r;
}

/**
 * EXAMPLE:
 */


echo makePassword(12);
?>
 

Chris M

Comments

Comments Small insecurity
Wed. Apr. 2nd, 2008 3:24 PM    Scripter sehrgut
Comments Revision 2
Tue. Oct. 10th, 2006 1:28 PM    Helper inxilpro

Voting