Dessert #3 - Generate a random password
Posted by Felix Geisendörfer, on Sep 15, 2006 - in PHP & CakePHP » Core & Hacking
Deprecated post
The authors of this post have marked it as deprecated. This means the information displayed is most likely outdated, inaccurate, boring or a combination of all three.
Policy: We never delete deprecated posts, but they are not listed in our categories or show up in the search anymore.
Comments: You can continue to leave comments on this post, but please consult Google or our search first if you want to get an answer ; ).
A neat function I just discovered while looking for a useful CakePHP tip to save me from putting my head into a cake is contained in the NeatString class which rests in /cake/libs/neat_string.php
The function of interest is NeatString::randomPassword($length, $available_chars) which can be used to create a random password with a given $length which is made out of the $available_chars. By default $available_chars contains [A-Z0-9] (All upper case letters + numbers), but you can extend it to use any characters you consider valid for a password (like underscores, dot's, etc.).
The usage of the function is rather simple, but let's take a look at a little example anyway:
Imagine you want to generate a simple password made up of 8 letters in your controller and display it to the user:
-
uses('neat_string');
-
$this->set('password', NeatString::randomPassword(8));
Or be a little bit more fancy and allow a whole bunch of other characters:
-
NeatString::randomPassword(8, '.,#[]()\$!/\\&+-§%=abcdefghijklmnopqrstuvwxyzABDEFHKMNPRTWXYABDEFHKMNPRTWXY23456789');
That's it. Usally you would use this to generate a new password for users that forgot their old one and mail it to them. Or in case you still store passwords in plain text here is another tip: Don't ever do that. Instead store the md5 hash (or some alternative) in the database and then compare the stored hash with the one of the password the user enters when logging in to check for authentication. That way even if you're app has a horrible security hole and somebody get's a hold of your users table, the passwords won't be visible to him. And in case you want to be even fancier, look for a hash algorithm that's available in javascript as well and perform the hashing of the password on the client side so that even a man in the middle attack wouldn't reveal the real password. Combined with a technique like 1-time-challenge you can also take care of replay attacks.
--Felix Geisendörfer aka the_undefined