In the last post, Generating Random Passwords 5 – Saving The Password, there was an issue with the passwords that were posted here. Did you catch it? They were not 32 characters long, even though I had specified that. Or rather, they had characters we could not see. These characters did not render, but were there.
To make things easy, and to ensure I do not have an encoding problem with my files, I’m going to switch to using a loop and the character integer values for the predefined pools of characters.
Here’s what that looks like in the function generateRandomPassword
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public static function generateRandomPassword(int $length = 12, $pool = '') { if (empty($pool)) { $pool = []; for ($iterator = 0x20; $iterator < 0x7F; $iterator++) { $pool[] = chr($iterator); } } elseif (is_string($pool)) { $pool = \str_split($pool); } $password = ''; $poolLength = \count($pool) - 1; for ($iterator = 0; $iterator < $length; $iterator++) { $password .= $pool[\random_int(0, $poolLength)]; } return $password; } |
You can see that I’m just adding the characters to the pool one-by-one using a loop. I’ve used the hexadecimal representation for the integer values, for another measure of safety.
Let’s update the function generateRandomPasswordUntypable
now.
29 30 31 32 33 34 35 36 37 38 39 40 41 |
public static function generateRandomPasswordUntypable(int $length = 12) { $pool = []; for ($iterator = 0x20; $iterator < 0x7F; $iterator++) { $pool[] = chr($iterator); } for ($iterator = 0xA0; $iterator < 0xFF; $iterator++) { $pool[] = Emoji::char($iterator); } var_dump($pool); return static::generateRandomPassword($length, $pool); } |
Notice here that I’m making a gap between 0x7F and 0xA0. This is because in my testing the characters that were in the range of 0x80 to 0x9F did not have a representation all of the time, in the console or here in this blog. This is the “trouble range” that was causing the passwords in the last post to appear to be missing characters.
Since generateRandomPasswordEmoji was based on GenerateRandomPassword we will update that function too.
43 44 45 46 47 48 49 50 51 52 53 54 55 |
public static function generateRandomPasswordEmoji(int $length = 12) { $pool = []; for ($iterator = 0x20; $iterator < 0x7F; $iterator++) { $pool[] = chr($iterator); } foreach (self::$dictionary as $k => $hex) { $pool[] = Emoji::char($k); } return static::generateRandomPassword($length, $pool); } |
The repository for this post can be found on GitHub here .
The repository for this post can be found on GitLab here .
The repository for this post can be found on Lupe Code’s GitLab mirror here .