3 * Password Hashing Class
5 * This class implements various mechanisms used to hash passwords
7 * @author Andreas Gohr <andi@splitbrain.org>
12 * Verifies a cleartext password against a crypted hash
14 * The method and salt used for the crypted hash is determined automatically,
15 * then the clear text password is crypted using the same method. If both hashs
16 * match true is is returned else false
18 * @author Andreas Gohr <andi@splitbrain.org>
19 * @param $clear string Clear-Text password
20 * @param $hash string Hash to compare against
23 function verify_hash($clear, $hash) {
28 //determine the used method and salt
30 if(preg_match('/^\$1\$([^\$]{0,8})\$/', $hash, $m)) {
34 } elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/', $hash, $m)) {
38 } elseif(preg_match('/^\$P\$(.{31})$/', $hash, $m)) {
42 } elseif(preg_match('/^\$H\$(.{31})$/', $hash, $m)) {
46 } elseif(preg_match('/^sha1\$(.{5})\$/', $hash, $m)) {
47 $method = 'djangosha1';
49 } elseif(preg_match('/^md5\$(.{5})\$/', $hash, $m)) {
50 $method = 'djangomd5';
52 } elseif(preg_match('/^\$2a\$(.{2})\$/', $hash, $m)) {
55 } elseif(substr($hash, 0, 6) == '{SSHA}') {
57 $salt = substr(base64_decode(substr($hash, 6)), 20);
58 } elseif(substr($hash, 0, 6) == '{SMD5}') {
60 $salt = substr(base64_decode(substr($hash, 6)), 16);
61 } elseif($len == 32) {
63 } elseif($len == 40) {
65 } elseif($len == 16) {
67 } elseif($len == 41 && $hash[0] == '*') {
69 } elseif($len == 34) {
74 $salt = substr($hash, 0, 2);
78 $call = 'hash_'.$method;
79 if($this->$call($clear, $salt, $magic) === $hash) {
86 * Create a random salt
88 * @param int $len The length of the salt
91 public function gen_salt($len = 32) {
93 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
94 for($i = 0; $i < $len; $i++) {
95 $salt .= $chars[mt_rand(0, 61)];
101 * Initialize the passed variable with a salt if needed.
103 * If $salt is not null, the value is kept, but the lenght restriction is
106 * @param string &$salt The salt, pass null if you want one generated
107 * @param int $len The length of the salt
109 public function init_salt(&$salt, $len = 32) {
110 if(is_null($salt)) $salt = $this->gen_salt($len);
111 if(strlen($salt) > $len) $salt = substr($salt, 0, $len);
114 // Password hashing methods follow below
117 * Password hashing method 'smd5'
119 * Uses salted MD5 hashs. Salt is 8 bytes long.
121 * The same mechanism is used by Apache's 'apr1' method. This will
122 * fallback to a implementation in pure PHP if MD5 support is not
123 * available in crypt()
125 * @author Andreas Gohr <andi@splitbrain.org>
126 * @author <mikey_nich at hotmail dot com>
127 * @link http://de.php.net/manual/en/function.crypt.php#73619
128 * @param string $clear The clear text to hash
129 * @param string $salt The salt to use, null for random
130 * @return string Hashed password
132 public function hash_smd5($clear, $salt = null) {
133 $this->init_salt($salt, 8);
135 if(defined('CRYPT_MD5') && CRYPT_MD5 && $salt !== '') {
136 return crypt($clear, '$1$'.$salt.'$');
138 // Fall back to PHP-only implementation
139 return $this->hash_apr1($clear, $salt, '1');
144 * Password hashing method 'lsmd5'
146 * Uses salted MD5 hashs. Salt is 8 bytes long.
148 * This is the format used by LDAP.
150 * @param string $clear The clear text to hash
151 * @param string $salt The salt to use, null for random
152 * @return string Hashed password
154 public function hash_lsmd5($clear, $salt = null) {
155 $this->init_salt($salt, 8);
156 return "{SMD5}".base64_encode(md5($clear.$salt, true).$salt);
160 * Password hashing method 'apr1'
162 * Uses salted MD5 hashs. Salt is 8 bytes long.
164 * This is basically the same as smd1 above, but as used by Apache.
166 * @author <mikey_nich at hotmail dot com>
167 * @link http://de.php.net/manual/en/function.crypt.php#73619
168 * @param string $clear The clear text to hash
169 * @param string $salt The salt to use, null for random
170 * @param string $magic The hash identifier (apr1 or 1)
171 * @return string Hashed password
173 public function hash_apr1($clear, $salt = null, $magic = 'apr1') {
174 $this->init_salt($salt, 8);
176 $len = strlen($clear);
177 $text = $clear.'$'.$magic.'$'.$salt;
178 $bin = pack("H32", md5($clear.$salt.$clear));
179 for($i = $len; $i > 0; $i -= 16) {
180 $text .= substr($bin, 0, min(16, $i));
182 for($i = $len; $i > 0; $i >>= 1) {
183 $text .= ($i & 1) ? chr(0) : $clear{0};
185 $bin = pack("H32", md5($text));
186 for($i = 0; $i < 1000; $i++) {
187 $new = ($i & 1) ? $clear : $bin;
188 if($i % 3) $new .= $salt;
189 if($i % 7) $new .= $clear;
190 $new .= ($i & 1) ? $bin : $clear;
191 $bin = pack("H32", md5($new));
194 for($i = 0; $i < 5; $i++) {
198 $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
200 $tmp = chr(0).chr(0).$bin[11].$tmp;
202 strrev(substr(base64_encode($tmp), 2)),
203 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
204 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
206 return '$'.$magic.'$'.$salt.'$'.$tmp;
210 * Password hashing method 'md5'
214 * @param string $clear The clear text to hash
215 * @return string Hashed password
217 public function hash_md5($clear) {
222 * Password hashing method 'sha1'
226 * @param string $clear The clear text to hash
227 * @return string Hashed password
229 public function hash_sha1($clear) {
234 * Password hashing method 'ssha' as used by LDAP
236 * Uses salted SHA1 hashs. Salt is 4 bytes long.
238 * @param string $clear The clear text to hash
239 * @param string $salt The salt to use, null for random
240 * @return string Hashed password
242 public function hash_ssha($clear, $salt = null) {
243 $this->init_salt($salt, 4);
244 return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
248 * Password hashing method 'crypt'
250 * Uses salted crypt hashs. Salt is 2 bytes long.
252 * @param string $clear The clear text to hash
253 * @param string $salt The salt to use, null for random
254 * @return string Hashed password
256 public function hash_crypt($clear, $salt = null) {
257 $this->init_salt($salt, 2);
258 return crypt($clear, $salt);
262 * Password hashing method 'mysql'
264 * This method was used by old MySQL systems
266 * @link http://www.php.net/mysql
267 * @author <soren at byu dot edu>
268 * @param string $clear The clear text to hash
269 * @return string Hashed password
271 public function hash_mysql($clear) {
275 $charArr = preg_split("//", $clear);
276 foreach($charArr as $char) {
277 if(($char == '') || ($char == ' ') || ($char == '\t')) continue;
278 $charVal = ord($char);
279 $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
280 $nr2 += ($nr2 << 8) ^ $nr;
283 return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
287 * Password hashing method 'my411'
289 * Uses SHA1 hashs. This method is used by MySQL 4.11 and above
291 * @param string $clear The clear text to hash
292 * @return string Hashed password
294 public function hash_my411($clear) {
295 return '*'.sha1(pack("H*", sha1($clear)));
299 * Password hashing method 'kmd5'
301 * Uses salted MD5 hashs.
303 * Salt is 2 bytes long, but stored at position 16, so you need to pass at
304 * least 18 bytes. You can pass the crypted hash as salt.
306 * @param string $clear The clear text to hash
307 * @param string $salt The salt to use, null for random
308 * @return string Hashed password
310 public function hash_kmd5($clear, $salt = null) {
311 $this->init_salt($salt);
313 $key = substr($salt, 16, 2);
314 $hash1 = strtolower(md5($key.md5($clear)));
315 $hash2 = substr($hash1, 0, 16).$key.substr($hash1, 16);
320 * Password hashing method 'pmd5'
322 * Uses salted MD5 hashs. Salt is 1+8 bytes long, 1st byte is the
323 * iteration count when given, for null salts $compute is used.
325 * The actual iteration count is the given count squared, maximum is
326 * 30 (-> 1073741824). If a higher one is given, the function throws
329 * @link http://www.openwall.com/phpass/
330 * @param string $clear The clear text to hash
331 * @param string $salt The salt to use, null for random
332 * @param string $magic The hash identifier (P or H)
333 * @param int $compute The iteration count for new passwords
335 * @return string Hashed password
337 public function hash_pmd5($clear, $salt = null, $magic = 'P', $compute = 8) {
338 $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
340 $this->init_salt($salt);
341 $salt = $itoa64[$compute].$salt; // prefix iteration count
343 $iterc = $salt[0]; // pos 0 of salt is iteration count
344 $iter = strpos($itoa64, $iterc);
347 throw new Exception("Too high iteration count ($iter) in ".
348 __CLASS__.'::'.__FUNCTION__);
352 $salt = substr($salt, 1, 8);
355 $hash = md5($salt.$clear, true);
357 $hash = md5($hash.$clear, true);
365 $value = ord($hash[$i++]);
366 $output .= $itoa64[$value & 0x3f];
368 $value |= ord($hash[$i]) << 8;
369 $output .= $itoa64[($value >> 6) & 0x3f];
373 $value |= ord($hash[$i]) << 16;
374 $output .= $itoa64[($value >> 12) & 0x3f];
377 $output .= $itoa64[($value >> 18) & 0x3f];
378 } while($i < $count);
380 return '$'.$magic.'$'.$iterc.$salt.$output;
384 * Alias for hash_pmd5
386 public function hash_hmd5($clear, $salt = null, $magic = 'H', $compute = 8) {
387 return $this->hash_pmd5($clear, $salt, $magic, $compute);
391 * Password hashing method 'djangosha1'
393 * Uses salted SHA1 hashs. Salt is 5 bytes long.
394 * This is used by the Django Python framework
396 * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords
397 * @param string $clear The clear text to hash
398 * @param string $salt The salt to use, null for random
399 * @return string Hashed password
401 public function hash_djangosha1($clear, $salt = null) {
402 $this->init_salt($salt, 5);
403 return 'sha1$'.$salt.'$'.sha1($salt.$clear);
407 * Password hashing method 'djangomd5'
409 * Uses salted MD5 hashs. Salt is 5 bytes long.
410 * This is used by the Django Python framework
412 * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords
413 * @param string $clear The clear text to hash
414 * @param string $salt The salt to use, null for random
415 * @return string Hashed password
417 public function hash_djangomd5($clear, $salt = null) {
418 $this->init_salt($salt, 5);
419 return 'md5$'.$salt.'$'.md5($salt.$clear);
423 * Passwordhashing method 'bcrypt'
425 * Uses a modified blowfish algorithm called eksblowfish
426 * This method works on PHP 5.3+ only and will throw an exception
427 * if the needed crypt support isn't available
429 * A full hash should be given as salt (starting with $a2$) or this
430 * will break. When no salt is given, the iteration count can be set
431 * through the $compute variable.
433 * @param string $clear The clear text to hash
434 * @param string $salt The salt to use, null for random
435 * @param int $compute The iteration count (between 4 and 31)
437 * @return string Hashed password
439 public function hash_bcrypt($clear, $salt = null, $compute = 8) {
440 if(!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH != 1) {
441 throw new Exception('This PHP installation has no bcrypt support');
445 if($compute < 4 || $compute > 31) $compute = 8;
446 $salt = '$2a$'.str_pad($compute, 2, '0', STR_PAD_LEFT).'$'.
450 return crypt($clear, $salt);