note 5932 deleted from function.crypt by jimw
| From: | jimw@php.net | Date: | Sat, 03 Nov 2001 18:16:35 +0000 |
| Subject: | note 5932 deleted from function.crypt by jimw | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-20366@lists.php.net to get a copy of this message | ||
I took the nice salt generator listed above and improved on it a little bit. It works well, I
needed to set up user authentication for a site I was working on, and I quested a bit the
information provided below, so enjoy!
function rannum(){
mt_srand((double)microtime()*1000000);
$num = mt_rand(46,122);
return $num;
}
function genchr(){
do{
$num = rannum();
} while ( ( $num > 57 && $num < 65 ) || ( $num > 90 && $num < 97 ) );
$char = chr($num);
return $char;
}
function saltstr($size){
for($i=1;$i<=$size;$i++) {
$string = $string.genchr();
}
return $string;
}
function gensalt($type){
if($type == "des-std") { /* des-standard salt (2 chr)
*/
return saltstr(2);
} else if ($type == "des-ext") { /* des-extended salt (9 chr)
*/
return saltstr(9);
} else if ($type == "md5") { /* md5 salt (12 char, starts with $1$ ends with $
*/
$tmpslt = saltstr(8);
return sprintf("$1$%s$",$tmpslt);
} else if ($type == "blowfish") { /* blowfish salt (16 char, starts with $2$ ends
with $ */
$tmpslt = saltstr(13);
return sprintf("$2$%s$",$tmpslt);
} else { /* Catch everything else to des-std */
return saltstr(2);
}
}
Then you just call $salt = gensalt("md5"); or ("des-std"); and it returns the
salt requested. Actually, you could feed it straight into crypt as the second argument.
If you are using des-std, md5, or blowfish, and are validating a password presented by a user
against a password stored, say from a database, just feed the database password as the salt to the
presented password. IE $stored being the password stored on the server, and $presented being the
password presented, you could do something like:
if ($stored == crypt($presented, $stored)) {
// Password valid
} else {
// Password invalid
}
Based on the first couple of characters ($1$, $2$, or nothing) it desides which crypt() method to
use, and crypts the password appropriately. So if it starts with $1$, it will md5 crypt the message
using the first 12 chars of the stored password (the salt). If $2$ it will use 16, and nothing it
will use two. I have no idea if it will work with des-ext, as I have no method of testing, however
I would assume so (based on overall crypted string length) but thats just a guess.
In any case, I quested for a bit for this and I hope this will help someone else questing for
information.