0

I am working on Yii. I want to generate 20 digit random keys. I had written a function as -

public function GenerateKey()
{
    //for generating random confirm key
     $length = 20;
     $chars = array_merge(range(0,9), range('a','z'), range('A','Z'));
     shuffle($chars);
     $password = implode(array_slice($chars, 0, $length));
     return $password;
}

This function is generating 20 digit key correctly. But I want the key in a format like
"g12a-Gh45-gjk7-nbj8-lhk8". i.e. separated by hypen. So what changes do I need to do?

bool.dev
  • 17,508
  • 5
  • 69
  • 93
user1722857
  • 877
  • 2
  • 19
  • 33

2 Answers2

0

You can use chunk_split() to add the hyphens. substr() is used to remove the trailing hyphen it adds, leaving only those hyphens that actually separate groups.

return substr(chunk_split($password, 4, '-'), 0, 24);

However, note that shuffle() not only uses a relatively poor PRNG but also will not allow the same character to be used twice. Instead, use mt_rand() in a for loop, and then using chunk_split() is easy to avoid:

$password = '';
for ($i = 0; $i < $length; $i++) {
    if ( $i != 0 && $i % 4 == 0 ) { // nonzero and divisible by 4
        $password .= '-';
    }
    $password .= $chars[mt_rand(0, count($chars) - 1)];
}
return $password;

(Even mt_rand() is not a cryptographically secure PRNG. If you need to generate something that must be extremely hard to predict (e.g. an encryption key or password reset token), use openssl_random_pseudo_bytes() to generate bytes and then a separate function such as bin2hex() to encode them into printable characters. I am not familiar with Yii, so I cannot say whether or not it has a function for this.)

PleaseStand
  • 31,641
  • 6
  • 68
  • 95
0

You can use this Yii internal function:

Yii::app()->getSecurityManager()->generateRandomString($length);
Saleh Hashemi
  • 329
  • 2
  • 11