mercredi 23 février 2022

What is the correct way to generate a CSPRNG string with specific rules in PHP?

Assume you want to generate a safe, random password with at least 8 characters in PHP, containing at least one uppercase, lowercase, number and special character.

I've read through some answers, basically all of them refer to here, this is why I choose RandomLib.

Unfortunately it doesn't seem to be possible to pass the "rules" to the generator.

My solution now is:

    $factory = new \RandomLib\Factory;
    $generator = $factory->getLowStrengthGenerator();
    $nums = $generator->generateString(random_int(1, 5), '0123456789');
    $capsStr = $generator->generateString(random_int(1, 6 - strlen($nums)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
    $lowerStr = $generator->generateString(random_int(1, 7 - strlen($nums) - strlen($capsStr)), 'abcdefghijklmnopqrstuvwxyz');
    $special = $generator->generateString(random_int(1, 8 - strlen($nums) - strlen($capsStr) - strlen($lowerStr)), '+-!$%&#*_.;:<>' );
    $password = str_shuffle($nums . $capsStr . $lowerStr . $special);
    var_dump($password);

But I have a feeling this is inefficient and could be done faster. I get a "wallclock" execution time of around 0.025 Seconds on average. Furthermore I'm adding the "unsafe" random_int method, which I tried to prevent by using RandomLib

Is there a safer/faster way to achieve this?




Aucun commentaire:

Enregistrer un commentaire