Jump to content

Function to generate a secure random password

Recommended Posts

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.

Link to comment
Share on other sites

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.