Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Random Password without these characters "l1o0"

I need to generate random password with condition:

  • All characters are allowable except "l1o0"
  • Length of 8 to 12 in characters

Codes I've tried:

function generateRandomPassword() {
  //Initialize the random password
  $password = '';

  //Initialize a random desired length
  $desired_length = rand(8, 12);

  for($length = 0; $length < $desired_length; $length++) {
    //Append a random ASCII character (including symbols)
    $password .= chr(rand(32, 126));
  }

  return $password;
}

How to avoid these 4 characters => "l1o0" ?

Reason:

  • These 4 characters are sometimes confused the user.

Thanks!

like image 732
Nere Avatar asked Oct 25 '15 09:10

Nere


1 Answers

Please don't use any of the other answers currently provided for generating passwords. They're not secure by any measure.

  • rand() -> No
  • mt_rand() -> Definitely not

I'm going to pull this solution from a blog post aptly titled How to Securely Generate Random Strings and Integers in PHP.

/**
 * Note: See https://paragonie.com/b/JvICXzh_jhLyt4y3 for an alternative implementation
 */
function random_string($length = 26, $alphabet = 'abcdefghijklmnopqrstuvwxyz234567')
{
    if ($length < 1) {
        throw new InvalidArgumentException('Length must be a positive integer');
    }
    $str = '';
    $alphamax = strlen($alphabet) - 1;
    if ($alphamax < 1) {
        throw new InvalidArgumentException('Invalid alphabet');
    }
    for ($i = 0; $i < $length; ++$i) {
        $str .= $alphabet[random_int(0, $alphamax)];
    }
    return $str;
}

Usage:

// Every ASCII alphanumeric except "loIO01":
$alphabet = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$string = random_string(12, $alphabet);

You probably don't have random_int(), unless you're reading this in the future when PHP 7 is released. For those of us living in the present, use random_compat.

like image 99
Scott Arciszewski Avatar answered Oct 12 '22 23:10

Scott Arciszewski