Reputation: 1
Basically I have a script that allows members to register, passwords currently must contain at least 1 lower-case, 1 upper-case, 1 numeric and 1 special character, the password must also be at least 8 characters in length.
On the registration and password change pages I want to suggest 3 randomly generated strong passwords but not sure if my methods are the best way of doing it.
basically i run substr(str_shuffle()); against 4 set of characters, the first is lower case, the second is upper case, the third is numeric and the fourth is special characters.
Certain letters/numbers have been ommitted such as zero and O to avoid confusion between the 2. I have also repeated each character to allow for the option of each character to be included more than once.
I then do a final substr(str_shuffle()) on the output of the first 4 results to generate a password that is 10 characters in length and contains at least 2 of each of lower-case, upper-case, numeric and special characters.
// Generates a secure random password
$random_LC = substr(str_shuffle("abcdefghjkmnpqrstuvwxyzabcdefghjkmnpqrstuvwxyz"), 0, 2);
$random_UC = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZABCDEFGHJKLMNPQRSTUVWXYZ"), 0, 2);
$random_NC = substr(str_shuffle("2345678923456789"), 0, 2);
$random_SC = substr(str_shuffle("@~#[]{}+&*%()£$\/<>@~#[]{}+&*%()£$\/<>"), 0, 4);
$random_PW = substr(str_shuffle("$random_LC$random_UC$random_NC$random_SC"), 0, 10);
$random_PW2 = substr(str_shuffle("$random_LC$random_UC$random_NC$random_SC"), 0, 10);
$random_PW3 = substr(str_shuffle("$random_LC$random_UC$random_NC$random_SC"), 0, 10);
The output could then be echoed through $random_PW, $random_PW2 etc.
A current example of what the above code outputs is
vH}[2p$W2&
5$/wM6q(\P
qM5w6/$\P(
$PM\/65w(q
I believe that if i simply did 1 substr(str_shuffle()) against all the characters there is a good chance that it would not meet the requirements of at least 1 of each character type being included in the output.
Is there an easier way to produce a random password that meets the above requirements?
Upvotes: 0
Views: 397
Reputation: 2596
I'd suggest also varying the length of the password.
Probably it would be better not to have a constant number of special characters, lower case letters, uppercase and numbers. You could make sure that you have at least one of these and generate a random variation of mixed characters.
Here's an improved version (that generates a password between 8 and 12 characters and meets the criteria that you required):
$chr = array_merge(
range('A', 'N'), range('P', 'Z'),
range('a', 'n'), range('p', 'z'),
range(2, 9), str_split('@~#[]{}+&*%()£$\/<>')
);
$password = $chr[mt_rand(0, 24)] . $chr[mt_rand(25, 49)]
. $chr[mt_rand(50, 57)] . $chr[mt_rand(58, 76)];
for ($i = rand(4, 8); $i >= 0; $i--) {
$password .= $chr[mt_rand(0, count($chr) - 1)];
}
$password = str_shuffle($password);
Upvotes: 1