[ Index ] |
PHP Cross Reference of DokuWiki |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * Password Hashing Class 4 * 5 * This class implements various mechanisms used to hash passwords 6 * 7 * @author Andreas Gohr <andi@splitbrain.org> 8 * @license LGPL2 9 */ 10 class PassHash { 11 /** 12 * Verifies a cleartext password against a crypted hash 13 * 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 17 * 18 * @author Andreas Gohr <andi@splitbrain.org> 19 * 20 * @param string $clear Clear-Text password 21 * @param string $hash Hash to compare against 22 * @return bool 23 */ 24 function verify_hash($clear, $hash) { 25 $method = ''; 26 $salt = ''; 27 $magic = ''; 28 29 //determine the used method and salt 30 $len = strlen($hash); 31 if(preg_match('/^\$1\$([^\$]{0,8})\$/', $hash, $m)) { 32 $method = 'smd5'; 33 $salt = $m[1]; 34 $magic = '1'; 35 } elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/', $hash, $m)) { 36 $method = 'apr1'; 37 $salt = $m[1]; 38 $magic = 'apr1'; 39 } elseif(preg_match('/^\$P\$(.{31})$/', $hash, $m)) { 40 $method = 'pmd5'; 41 $salt = $m[1]; 42 $magic = 'P'; 43 } elseif(preg_match('/^\$H\$(.{31})$/', $hash, $m)) { 44 $method = 'pmd5'; 45 $salt = $m[1]; 46 $magic = 'H'; 47 } elseif(preg_match('/^pbkdf2_(\w+?)\$(\d+)\$(.{12})\$/', $hash, $m)) { 48 $method = 'djangopbkdf2'; 49 $magic = array( 50 'algo' => $m[1], 51 'iter' => $m[2], 52 ); 53 $salt = $m[3]; 54 } elseif(preg_match('/^sha1\$(.{5})\$/', $hash, $m)) { 55 $method = 'djangosha1'; 56 $salt = $m[1]; 57 } elseif(preg_match('/^md5\$(.{5})\$/', $hash, $m)) { 58 $method = 'djangomd5'; 59 $salt = $m[1]; 60 } elseif(preg_match('/^\$2(a|y)\$(.{2})\$/', $hash, $m)) { 61 $method = 'bcrypt'; 62 $salt = $hash; 63 } elseif(substr($hash, 0, 6) == '{SSHA}') { 64 $method = 'ssha'; 65 $salt = substr(base64_decode(substr($hash, 6)), 20); 66 } elseif(substr($hash, 0, 6) == '{SMD5}') { 67 $method = 'lsmd5'; 68 $salt = substr(base64_decode(substr($hash, 6)), 16); 69 } elseif(preg_match('/^:B:(.+?):.{32}$/', $hash, $m)) { 70 $method = 'mediawiki'; 71 $salt = $m[1]; 72 } elseif(preg_match('/^\$6\$(rounds=\d+)?\$?(.+?)\$/', $hash, $m)) { 73 $method = 'sha512'; 74 $salt = $m[2]; 75 $magic = $m[1]; 76 } elseif($len == 32) { 77 $method = 'md5'; 78 } elseif($len == 40) { 79 $method = 'sha1'; 80 } elseif($len == 16) { 81 $method = 'mysql'; 82 } elseif($len == 41 && $hash[0] == '*') { 83 $method = 'my411'; 84 } elseif($len == 34) { 85 $method = 'kmd5'; 86 $salt = $hash; 87 } else { 88 $method = 'crypt'; 89 $salt = substr($hash, 0, 2); 90 } 91 92 //crypt and compare 93 $call = 'hash_'.$method; 94 $newhash = $this->$call($clear, $salt, $magic); 95 if(\hash_equals($newhash, $hash)) { 96 return true; 97 } 98 return false; 99 } 100 101 /** 102 * Create a random salt 103 * 104 * @param int $len The length of the salt 105 * @return string 106 */ 107 public function gen_salt($len = 32) { 108 $salt = ''; 109 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 110 for($i = 0; $i < $len; $i++) { 111 $salt .= $chars[$this->random(0, 61)]; 112 } 113 return $salt; 114 } 115 116 /** 117 * Initialize the passed variable with a salt if needed. 118 * 119 * If $salt is not null, the value is kept, but the lenght restriction is 120 * applied (unless, $cut is false). 121 * 122 * @param string|null &$salt The salt, pass null if you want one generated 123 * @param int $len The length of the salt 124 * @param bool $cut Apply length restriction to existing salt? 125 */ 126 public function init_salt(&$salt, $len = 32, $cut = true) { 127 if(is_null($salt)) { 128 $salt = $this->gen_salt($len); 129 $cut = true; // for new hashes we alway apply length restriction 130 } 131 if(strlen($salt) > $len && $cut) $salt = substr($salt, 0, $len); 132 } 133 134 // Password hashing methods follow below 135 136 /** 137 * Password hashing method 'smd5' 138 * 139 * Uses salted MD5 hashs. Salt is 8 bytes long. 140 * 141 * The same mechanism is used by Apache's 'apr1' method. This will 142 * fallback to a implementation in pure PHP if MD5 support is not 143 * available in crypt() 144 * 145 * @author Andreas Gohr <andi@splitbrain.org> 146 * @author <mikey_nich at hotmail dot com> 147 * @link http://php.net/manual/en/function.crypt.php#73619 148 * 149 * @param string $clear The clear text to hash 150 * @param string $salt The salt to use, null for random 151 * @return string Hashed password 152 */ 153 public function hash_smd5($clear, $salt = null) { 154 $this->init_salt($salt, 8); 155 156 if(defined('CRYPT_MD5') && CRYPT_MD5 && $salt !== '') { 157 return crypt($clear, '$1$'.$salt.'$'); 158 } else { 159 // Fall back to PHP-only implementation 160 return $this->hash_apr1($clear, $salt, '1'); 161 } 162 } 163 164 /** 165 * Password hashing method 'lsmd5' 166 * 167 * Uses salted MD5 hashs. Salt is 8 bytes long. 168 * 169 * This is the format used by LDAP. 170 * 171 * @param string $clear The clear text to hash 172 * @param string $salt The salt to use, null for random 173 * @return string Hashed password 174 */ 175 public function hash_lsmd5($clear, $salt = null) { 176 $this->init_salt($salt, 8); 177 return "{SMD5}".base64_encode(md5($clear.$salt, true).$salt); 178 } 179 180 /** 181 * Password hashing method 'apr1' 182 * 183 * Uses salted MD5 hashs. Salt is 8 bytes long. 184 * 185 * This is basically the same as smd1 above, but as used by Apache. 186 * 187 * @author <mikey_nich at hotmail dot com> 188 * @link http://php.net/manual/en/function.crypt.php#73619 189 * 190 * @param string $clear The clear text to hash 191 * @param string $salt The salt to use, null for random 192 * @param string $magic The hash identifier (apr1 or 1) 193 * @return string Hashed password 194 */ 195 public function hash_apr1($clear, $salt = null, $magic = 'apr1') { 196 $this->init_salt($salt, 8); 197 198 $len = strlen($clear); 199 $text = $clear.'$'.$magic.'$'.$salt; 200 $bin = pack("H32", md5($clear.$salt.$clear)); 201 for($i = $len; $i > 0; $i -= 16) { 202 $text .= substr($bin, 0, min(16, $i)); 203 } 204 for($i = $len; $i > 0; $i >>= 1) { 205 $text .= ($i & 1) ? chr(0) : $clear{0}; 206 } 207 $bin = pack("H32", md5($text)); 208 for($i = 0; $i < 1000; $i++) { 209 $new = ($i & 1) ? $clear : $bin; 210 if($i % 3) $new .= $salt; 211 if($i % 7) $new .= $clear; 212 $new .= ($i & 1) ? $bin : $clear; 213 $bin = pack("H32", md5($new)); 214 } 215 $tmp = ''; 216 for($i = 0; $i < 5; $i++) { 217 $k = $i + 6; 218 $j = $i + 12; 219 if($j == 16) $j = 5; 220 $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp; 221 } 222 $tmp = chr(0).chr(0).$bin[11].$tmp; 223 $tmp = strtr( 224 strrev(substr(base64_encode($tmp), 2)), 225 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", 226 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 227 ); 228 return '$'.$magic.'$'.$salt.'$'.$tmp; 229 } 230 231 /** 232 * Password hashing method 'md5' 233 * 234 * Uses MD5 hashs. 235 * 236 * @param string $clear The clear text to hash 237 * @return string Hashed password 238 */ 239 public function hash_md5($clear) { 240 return md5($clear); 241 } 242 243 /** 244 * Password hashing method 'sha1' 245 * 246 * Uses SHA1 hashs. 247 * 248 * @param string $clear The clear text to hash 249 * @return string Hashed password 250 */ 251 public function hash_sha1($clear) { 252 return sha1($clear); 253 } 254 255 /** 256 * Password hashing method 'ssha' as used by LDAP 257 * 258 * Uses salted SHA1 hashs. Salt is 4 bytes long. 259 * 260 * @param string $clear The clear text to hash 261 * @param string $salt The salt to use, null for random 262 * @return string Hashed password 263 */ 264 public function hash_ssha($clear, $salt = null) { 265 $this->init_salt($salt, 4); 266 return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt); 267 } 268 269 /** 270 * Password hashing method 'crypt' 271 * 272 * Uses salted crypt hashs. Salt is 2 bytes long. 273 * 274 * @param string $clear The clear text to hash 275 * @param string $salt The salt to use, null for random 276 * @return string Hashed password 277 */ 278 public function hash_crypt($clear, $salt = null) { 279 $this->init_salt($salt, 2); 280 return crypt($clear, $salt); 281 } 282 283 /** 284 * Password hashing method 'mysql' 285 * 286 * This method was used by old MySQL systems 287 * 288 * @link http://php.net/mysql 289 * @author <soren at byu dot edu> 290 * @param string $clear The clear text to hash 291 * @return string Hashed password 292 */ 293 public function hash_mysql($clear) { 294 $nr = 0x50305735; 295 $nr2 = 0x12345671; 296 $add = 7; 297 $charArr = preg_split("//", $clear); 298 foreach($charArr as $char) { 299 if(($char == '') || ($char == ' ') || ($char == '\t')) continue; 300 $charVal = ord($char); 301 $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8); 302 $nr2 += ($nr2 << 8) ^ $nr; 303 $add += $charVal; 304 } 305 return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff)); 306 } 307 308 /** 309 * Password hashing method 'my411' 310 * 311 * Uses SHA1 hashs. This method is used by MySQL 4.11 and above 312 * 313 * @param string $clear The clear text to hash 314 * @return string Hashed password 315 */ 316 public function hash_my411($clear) { 317 return '*'.strtoupper(sha1(pack("H*", sha1($clear)))); 318 } 319 320 /** 321 * Password hashing method 'kmd5' 322 * 323 * Uses salted MD5 hashs. 324 * 325 * Salt is 2 bytes long, but stored at position 16, so you need to pass at 326 * least 18 bytes. You can pass the crypted hash as salt. 327 * 328 * @param string $clear The clear text to hash 329 * @param string $salt The salt to use, null for random 330 * @return string Hashed password 331 */ 332 public function hash_kmd5($clear, $salt = null) { 333 $this->init_salt($salt); 334 335 $key = substr($salt, 16, 2); 336 $hash1 = strtolower(md5($key.md5($clear))); 337 $hash2 = substr($hash1, 0, 16).$key.substr($hash1, 16); 338 return $hash2; 339 } 340 341 /** 342 * Password hashing method 'pmd5' 343 * 344 * Uses salted MD5 hashs. Salt is 1+8 bytes long, 1st byte is the 345 * iteration count when given, for null salts $compute is used. 346 * 347 * The actual iteration count is the given count squared, maximum is 348 * 30 (-> 1073741824). If a higher one is given, the function throws 349 * an exception. 350 * 351 * @link http://www.openwall.com/phpass/ 352 * 353 * @param string $clear The clear text to hash 354 * @param string $salt The salt to use, null for random 355 * @param string $magic The hash identifier (P or H) 356 * @param int $compute The iteration count for new passwords 357 * @throws Exception 358 * @return string Hashed password 359 */ 360 public function hash_pmd5($clear, $salt = null, $magic = 'P', $compute = 8) { 361 $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; 362 if(is_null($salt)) { 363 $this->init_salt($salt); 364 $salt = $itoa64[$compute].$salt; // prefix iteration count 365 } 366 $iterc = $salt[0]; // pos 0 of salt is iteration count 367 $iter = strpos($itoa64, $iterc); 368 369 if($iter > 30) { 370 throw new Exception("Too high iteration count ($iter) in ". 371 __CLASS__.'::'.__FUNCTION__); 372 } 373 374 $iter = 1 << $iter; 375 $salt = substr($salt, 1, 8); 376 377 // iterate 378 $hash = md5($salt.$clear, true); 379 do { 380 $hash = md5($hash.$clear, true); 381 } while(--$iter); 382 383 // encode 384 $output = ''; 385 $count = 16; 386 $i = 0; 387 do { 388 $value = ord($hash[$i++]); 389 $output .= $itoa64[$value & 0x3f]; 390 if($i < $count) 391 $value |= ord($hash[$i]) << 8; 392 $output .= $itoa64[($value >> 6) & 0x3f]; 393 if($i++ >= $count) 394 break; 395 if($i < $count) 396 $value |= ord($hash[$i]) << 16; 397 $output .= $itoa64[($value >> 12) & 0x3f]; 398 if($i++ >= $count) 399 break; 400 $output .= $itoa64[($value >> 18) & 0x3f]; 401 } while($i < $count); 402 403 return '$'.$magic.'$'.$iterc.$salt.$output; 404 } 405 406 /** 407 * Alias for hash_pmd5 408 * 409 * @param string $clear 410 * @param null|string $salt 411 * @param string $magic 412 * @param int $compute 413 * 414 * @return string 415 */ 416 public function hash_hmd5($clear, $salt = null, $magic = 'H', $compute = 8) { 417 return $this->hash_pmd5($clear, $salt, $magic, $compute); 418 } 419 420 /** 421 * Password hashing method 'djangosha1' 422 * 423 * Uses salted SHA1 hashs. Salt is 5 bytes long. 424 * This is used by the Django Python framework 425 * 426 * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords 427 * 428 * @param string $clear The clear text to hash 429 * @param string $salt The salt to use, null for random 430 * @return string Hashed password 431 */ 432 public function hash_djangosha1($clear, $salt = null) { 433 $this->init_salt($salt, 5); 434 return 'sha1$'.$salt.'$'.sha1($salt.$clear); 435 } 436 437 /** 438 * Password hashing method 'djangomd5' 439 * 440 * Uses salted MD5 hashs. Salt is 5 bytes long. 441 * This is used by the Django Python framework 442 * 443 * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords 444 * 445 * @param string $clear The clear text to hash 446 * @param string $salt The salt to use, null for random 447 * @return string Hashed password 448 */ 449 public function hash_djangomd5($clear, $salt = null) { 450 $this->init_salt($salt, 5); 451 return 'md5$'.$salt.'$'.md5($salt.$clear); 452 } 453 454 /** 455 * Password hashing method 'djangopbkdf2' 456 * 457 * An algorithm and iteration count should be given in the opts array. 458 * Defaults to sha256 and 24000 iterations 459 * 460 * @param string $clear The clear text to hash 461 * @param string $salt The salt to use, null for random 462 * @param array $opts ('algo' => hash algorithm, 'iter' => iterations) 463 * @return string Hashed password 464 * @throws Exception when PHP is missing support for the method/algo 465 */ 466 public function hash_djangopbkdf2($clear, $salt=null, $opts=array()) { 467 $this->init_salt($salt, 12); 468 if(empty($opts['algo'])) { 469 $algo = 'sha256'; 470 } else { 471 $algo = $opts['algo']; 472 } 473 if(empty($opts['iter'])) { 474 $iter = 24000; 475 } else { 476 $iter = (int) $opts['iter']; 477 } 478 if(!function_exists('hash_pbkdf2')) { 479 throw new Exception('This PHP installation has no PBKDF2 support'); 480 } 481 if(!in_array($algo, hash_algos())) { 482 throw new Exception("This PHP installation has no $algo support"); 483 } 484 485 $hash = base64_encode(hash_pbkdf2($algo, $clear, $salt, $iter, 0, true)); 486 return "pbkdf2_$algo\$$iter\$$salt\$$hash"; 487 } 488 489 /** 490 * Alias for djangopbkdf2 defaulting to sha256 as hash algorithm 491 * 492 * @param string $clear The clear text to hash 493 * @param string $salt The salt to use, null for random 494 * @param array $opts ('iter' => iterations) 495 * @return string Hashed password 496 * @throws Exception when PHP is missing support for the method/algo 497 */ 498 public function hash_djangopbkdf2_sha256($clear, $salt=null, $opts=array()) { 499 $opts['algo'] = 'sha256'; 500 return $this->hash_djangopbkdf2($clear, $salt, $opts); 501 } 502 503 /** 504 * Alias for djangopbkdf2 defaulting to sha1 as hash algorithm 505 * 506 * @param string $clear The clear text to hash 507 * @param string $salt The salt to use, null for random 508 * @param array $opts ('iter' => iterations) 509 * @return string Hashed password 510 * @throws Exception when PHP is missing support for the method/algo 511 */ 512 public function hash_djangopbkdf2_sha1($clear, $salt=null, $opts=array()) { 513 $opts['algo'] = 'sha1'; 514 return $this->hash_djangopbkdf2($clear, $salt, $opts); 515 } 516 517 /** 518 * Passwordhashing method 'bcrypt' 519 * 520 * Uses a modified blowfish algorithm called eksblowfish 521 * This method works on PHP 5.3+ only and will throw an exception 522 * if the needed crypt support isn't available 523 * 524 * A full hash should be given as salt (starting with $a2$) or this 525 * will break. When no salt is given, the iteration count can be set 526 * through the $compute variable. 527 * 528 * @param string $clear The clear text to hash 529 * @param string $salt The salt to use, null for random 530 * @param int $compute The iteration count (between 4 and 31) 531 * @throws Exception 532 * @return string Hashed password 533 */ 534 public function hash_bcrypt($clear, $salt = null, $compute = 10) { 535 if(!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH != 1) { 536 throw new Exception('This PHP installation has no bcrypt support'); 537 } 538 539 if(is_null($salt)) { 540 if($compute < 4 || $compute > 31) $compute = 8; 541 $salt = '$2y$'.str_pad($compute, 2, '0', STR_PAD_LEFT).'$'. 542 $this->gen_salt(22); 543 } 544 545 return crypt($clear, $salt); 546 } 547 548 /** 549 * Password hashing method SHA512 550 * 551 * This is only supported on PHP 5.3.2 or higher and will throw an exception if 552 * the needed crypt support is not available 553 * 554 * @param string $clear The clear text to hash 555 * @param string $salt The salt to use, null for random 556 * @param string $magic The rounds for sha512 (for example "rounds=3000"), null for default value 557 * @return string Hashed password 558 * @throws Exception 559 */ 560 public function hash_sha512($clear, $salt = null, $magic = null) { 561 if(!defined('CRYPT_SHA512') || CRYPT_SHA512 != 1) { 562 throw new Exception('This PHP installation has no SHA512 support'); 563 } 564 $this->init_salt($salt, 8, false); 565 if(empty($magic)) { 566 return crypt($clear, '$6$'.$salt.'$'); 567 }else{ 568 return crypt($clear, '$6$'.$magic.'$'.$salt.'$'); 569 } 570 } 571 572 /** 573 * Password hashing method 'mediawiki' 574 * 575 * Uses salted MD5, this is referred to as Method B in MediaWiki docs. Unsalted md5 576 * method 'A' is not supported. 577 * 578 * @link http://www.mediawiki.org/wiki/Manual_talk:User_table#user_password_column 579 * 580 * @param string $clear The clear text to hash 581 * @param string $salt The salt to use, null for random 582 * @return string Hashed password 583 */ 584 public function hash_mediawiki($clear, $salt = null) { 585 $this->init_salt($salt, 8, false); 586 return ':B:'.$salt.':'.md5($salt.'-'.md5($clear)); 587 } 588 589 /** 590 * Wraps around native hash_hmac() or reimplents it 591 * 592 * This is not directly used as password hashing method, and thus isn't callable via the 593 * verify_hash() method. It should be used to create signatures and might be used in other 594 * password hashing methods. 595 * 596 * @see hash_hmac() 597 * @author KC Cloyd 598 * @link http://php.net/manual/en/function.hash-hmac.php#93440 599 * 600 * @param string $algo Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", 601 * etc..) See hash_algos() for a list of supported algorithms. 602 * @param string $data Message to be hashed. 603 * @param string $key Shared secret key used for generating the HMAC variant of the message digest. 604 * @param bool $raw_output When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits. 605 * @return string 606 */ 607 public static function hmac($algo, $data, $key, $raw_output = false) { 608 // use native function if available and not in unit test 609 if(function_exists('hash_hmac') && !defined('SIMPLE_TEST')){ 610 return hash_hmac($algo, $data, $key, $raw_output); 611 } 612 613 $algo = strtolower($algo); 614 $pack = 'H' . strlen($algo('test')); 615 $size = 64; 616 $opad = str_repeat(chr(0x5C), $size); 617 $ipad = str_repeat(chr(0x36), $size); 618 619 if(strlen($key) > $size) { 620 $key = str_pad(pack($pack, $algo($key)), $size, chr(0x00)); 621 } else { 622 $key = str_pad($key, $size, chr(0x00)); 623 } 624 625 for($i = 0; $i < strlen($key) - 1; $i++) { 626 $opad[$i] = $opad[$i] ^ $key[$i]; 627 $ipad[$i] = $ipad[$i] ^ $key[$i]; 628 } 629 630 $output = $algo($opad . pack($pack, $algo($ipad . $data))); 631 632 return ($raw_output) ? pack($pack, $output) : $output; 633 } 634 635 /** 636 * Use DokuWiki's secure random generator if available 637 * 638 * @param int $min 639 * @param int $max 640 * @return int 641 */ 642 protected function random($min, $max){ 643 return random_int($min, $max); 644 } 645 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body