Jump to content


Photo

Function to generate a secure random password

password random generate generator secure

  • Please log in to reply
No replies to this topic

#1 Christian F.

Christian F.

    Advanced Member

  • Staff Alumni
  • 3,106 posts
  • LocationNorway

Posted 20 February 2013 - 06:13 PM

As a part of a project I'm working on, I just updated an old function of mine. Seeing as a lot of people still keep using time-based[1] techniques for generating password, I thought I should share this one with you all. Hopefully someone will find it useful. :)
 

/**
* Generates and returns a random password, of a random length between min and max.
*
* Hard limits are minimum 10 chars and maximum 72.
*
* @author Christian Fagerheim (Fagerheim Software)
* @link www.fagsoft.no
* @license Creative Commons Attribution-ShareAlike 3.0. http://creativecommons.org/licenses/by-sa/3.0/.
*
* @param int[optional] $minLen = 10
* @param int[optional] $maxLen = 14
* @return string
*/
function generatePassword ($minLen = 10, $maxLen = 14) {
    if ($minLen < 10) {
        $minLen = 10;
    }

    // Discard everything above 72 characters for the password (bcrypt limitation).
    if ($maxLen > 72) {
        $maxLen = 72;
    }

    $numChars = mt_rand ($minLen, $maxLen);

    // Create an secure random password, and cut it down to length.
    $password = base64_encode (mcrypt_create_iv (256, MCRYPT_DEV_URANDOM));
    $password = substr ($password, 0, $numChars);

    // Define the replacements sets and values for strtr ().
    $find = "10lIO";
    $replace = "_-*!?";

    // Replace the similar-looking characters with special characters.
    $password = strtr ($password, $find, $replace);

    // Save the hashed password in the object, and return it to calling method.
    return $password;
}

 

 

A copy can be found here: http://pastebin.com/se0YfEx1

[1]Time-based techniques are bad because they are very easy to predict, meaning that an attacked can quite easily guess the generated value as long as he knows the time of a request. Something which completely invalidates the point of having it be random in the first place.


Keeping it simple.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com