A Simple PHP Password Generation Function
Page last updated on 2011 / 04 / 09Passwords may well become a thing of the past in the not-so-distant future, as processing power doubles up year on year and makes the cracking of passwords in a brute force manner almost trivial.
This calculator of password complexity against brute force attacks shows how easy it is to compromise a password in an offline environment.
Fortunately for us web developers, things take an awful lot longer in an online scenario- mainly due to the fact that the online network is much slower than the electronics of a single box. Various other layers of protection can be added too, blaclistings IP's, locking accounts after a number of failed login attempts etc.
However, if somehow your filesystem/database gets compromised and becomes viewable by an untrusted source, you will hopefully have passwords encrypted!
If you are generating passwords for your users, you will want to have a level of complexity that won't be subject to brute force attacks.
The following code is a simple PHP password generator that will include alphanumeric characters and optionally other printable characters.
<?php function generate_password($length) { $chars = '.!,$%^&*@'; $clen = strlen($chars); $password = substr(base_convert(substr(md5(microtime()),1),16,36),0,$length); $len = strlen($password); for($i = 0;$i < $len;$i++) { if(rand(0,1) & 1) $password[$i] = strtoupper($password[$i]); elseif(rand(0,2) & 1 && $clen) $password[$i] = $chars[rand(0,$clen)]; } return $password; } echo generate_password(10),"\n"; ?>
You can determine the length by passing it into the function. If you would prefer not to have the non-alphanumeric characters (they help increase the password complexity. Just change the $chars variable into an empty string.
Tweet