I need to generate a random password containing 8 characters. The password must comply to below policy --
A Password should
- contain a minimum of one (1) non-alphabetic character
- not contain more than two (2) consecutive repeated characters
I am generating my password using below function.
function random_pass() {
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 7) {
$num = rand() % 60;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
And I have written below validation function that checks if the generated password is according to password policy
function password_policy($string)
{
// contains a minimum of one (1) non-alphabetic character
$r1 = '/[^a-zA-Z]+/';
// contains more than two (2) consecutive repeated characters
$r2 = '/(.)\\1{2}/';
if (preg_match_all($r1,$string, $o)<1) {
return "invalid - all alphabetic";
}
if (!preg_match_all($r2,$string, $o)<1) {
return "invalid - more than 2 consecutive repeated chars";
}
return "valid";
}
My random_pass doesn't work accurately all the time. Out 5-10 times out of 100, my password fails to comply with the password policy.
for ($j=0;$j<100;$j++) {
$pass = random_pass();
$validation = password_policy($pass);
if ($validation !== 'valid') {
print_r("$pass -- $validation\n");
}
}
-- output --
BCZHDgKl -- invalid - all alphabetic
xfCKKKH3 -- invalid - more than 2 consecutive repeated chars
aMtcWqEx -- invalid - all alphabetic
ZtpDGeKU -- invalid - all alphabetic
How do I generate such password that will 100% comply to aforementioned policy.
Please help me out. Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire