Generating Random Passwords
Writing a sufficient password generator does not have to be hard nor overly complex. In this article a simple password generator technique will be presented and explained.
One of the simplest password generators could simply output the ASCII character represented by a series of random integers:
Output specified amount of random characters by translating integers to ASCII characters:
<php
function GeneratePassword($len) {
for ( $i = 0; $i < $len; $i++ ) { $s .= chr(rand(32,126)); }
return $s;
}
print GeneratePassword(5);
?>
This might result in something like:
R,v4Cn b3×3J %Q_Oi
This approach works well but the fact that it will output any character in the ASCII table is not very appealing when it comes to creating memorable passwords and enter them into systems that will not allow certain character for some reasons. Filtering out the wanted ranges of characters becomes a tedious and code wasting job. There must be some other way!
By providing the password generator with a list of allowed characters it is easy to meet both needs.
The following function uses a random integer to match characters in a string and output a specified amount of them:
<?php
function GeneratePassword($len) {
$p="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ";
for( $i=0; $i < $len; $i++) { $s. = $p{rand(0,strlen($p))}; }
return $s;
}
print GeneratePassword(5);
?>
Example result will only contain characters from the string:
oclRK 9uSTl 2lJJL
By extending the string holding the possible characters the unique combinations of passwords grow which will result in safe passwords.