1<?php 2 3// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps 4 5namespace dokuwiki; 6 7/** 8 * Password Hashing Class 9 * 10 * This class implements various mechanisms used to hash passwords 11 * 12 * @author Andreas Gohr <andi@splitbrain.org> 13 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net> 14 * @license LGPL2 15 */ 16class PassHash 17{ 18 /** 19 * Verifies a cleartext password against a crypted hash 20 * 21 * The method and salt used for the crypted hash is determined automatically, 22 * then the clear text password is crypted using the same method. If both hashs 23 * match true is is returned else false 24 * 25 * @author Andreas Gohr <andi@splitbrain.org> 26 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net> 27 * 28 * @param string $clear Clear-Text password 29 * @param string $hash Hash to compare against 30 * @return bool 31 */ 32 public function verify_hash($clear, $hash) 33 { 34 $method = ''; 35 $salt = ''; 36 $magic = ''; 37 38 //determine the used method and salt 39 if (str_starts_with($hash, 'U$')) { 40 // This may be an updated password from user_update_7000(). Such hashes 41 // have 'U' added as the first character and need an extra md5(). 42 $hash = substr($hash, 1); 43 $clear = md5($clear); 44 } 45 $len = strlen($hash); 46 if (preg_match('/^\$1\$([^\$]{0,8})\$/', $hash, $m)) { 47 $method = 'smd5'; 48 $salt = $m[1]; 49 $magic = '1'; 50 } elseif (preg_match('/^\$apr1\$([^\$]{0,8})\$/', $hash, $m)) { 51 $method = 'apr1'; 52 $salt = $m[1]; 53 $magic = 'apr1'; 54 } elseif (preg_match('/^\$S\$(.{52})$/', $hash, $m)) { 55 $method = 'drupal_sha512'; 56 $salt = $m[1]; 57 $magic = 'S'; 58 } elseif (preg_match('/^\$P\$(.{31})$/', $hash, $m)) { 59 $method = 'pmd5'; 60 $salt = $m[1]; 61 $magic = 'P'; 62 } elseif (preg_match('/^\$H\$(.{31})$/', $hash, $m)) { 63 $method = 'pmd5'; 64 $salt = $m[1]; 65 $magic = 'H'; 66 } elseif (preg_match('/^pbkdf2_(\w+?)\$(\d+)\$(.{12})\$/', $hash, $m)) { 67 $method = 'djangopbkdf2'; 68 $magic = ['algo' => $m[1], 'iter' => $m[2]]; 69 $salt = $m[3]; 70 } elseif (preg_match('/^PBKDF2(SHA\d+)\$(\d+)\$([[:xdigit:]]+)\$([[:xdigit:]]+)$/', $hash, $m)) { 71 $method = 'seafilepbkdf2'; 72 $magic = ['algo' => $m[1], 'iter' => $m[2]]; 73 $salt = $m[3]; 74 } elseif (preg_match('/^sha1\$(.{5})\$/', $hash, $m)) { 75 $method = 'djangosha1'; 76 $salt = $m[1]; 77 } elseif (preg_match('/^md5\$(.{5})\$/', $hash, $m)) { 78 $method = 'djangomd5'; 79 $salt = $m[1]; 80 } elseif (preg_match('/^\$2([abxy])\$(.{2})\$/', $hash, $m)) { 81 $method = 'bcrypt'; 82 $salt = $hash; 83 } elseif (str_starts_with($hash, 'Bcrypt:$2')) { 84 $method = 'woltlab'; 85 $salt = substr($hash, 7); 86 } elseif (str_starts_with($hash, '{SSHA}')) { 87 $method = 'ssha'; 88 $salt = substr(base64_decode(substr($hash, 6)), 20); 89 } elseif (str_starts_with($hash, '{SMD5}')) { 90 $method = 'lsmd5'; 91 $salt = substr(base64_decode(substr($hash, 6)), 16); 92 } elseif (preg_match('/^:B:(.+?):.{32}$/', $hash, $m)) { 93 $method = 'mediawiki'; 94 $salt = $m[1]; 95 } elseif (preg_match('/^\$(5|6)\$(rounds=\d+)?\$?(.+?)\$/', $hash, $m)) { 96 $method = 'sha2'; 97 $salt = $m[3]; 98 $magic = ['prefix' => $m[1], 'rounds' => $m[2]]; 99 } elseif (preg_match('/^\$(argon2id?)/', $hash, $m)) { 100 if (!defined('PASSWORD_' . strtoupper($m[1]))) { 101 throw new \Exception('This PHP installation has no ' . strtoupper($m[1]) . ' support'); 102 } 103 return password_verify($clear, $hash); 104 } elseif ($len == 32) { 105 $method = 'md5'; 106 } elseif ($len == 40) { 107 $method = 'sha1'; 108 } elseif ($len == 16) { 109 $method = 'mysql'; 110 } elseif ($len == 41 && $hash[0] == '*') { 111 $method = 'my411'; 112 } elseif ($len == 34) { 113 $method = 'kmd5'; 114 $salt = $hash; 115 } else { 116 $method = 'crypt'; 117 $salt = substr($hash, 0, 2); 118 } 119 120 //crypt and compare 121 $call = 'hash_' . $method; 122 $newhash = $this->$call($clear, $salt, $magic); 123 if (\hash_equals($newhash, $hash)) { 124 return true; 125 } 126 return false; 127 } 128 129 /** 130 * Create a random salt 131 * 132 * @param int $len The length of the salt 133 * @return string 134 */ 135 public function gen_salt($len = 32) 136 { 137 $salt = ''; 138 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 139 for ($i = 0; $i < $len; $i++) { 140 $salt .= $chars[$this->random(0, 61)]; 141 } 142 return $salt; 143 } 144 145 /** 146 * Initialize the passed variable with a salt if needed. 147 * 148 * If $salt is not null, the value is kept, but the lenght restriction is 149 * applied (unless, $cut is false). 150 * 151 * @param string|null &$salt The salt, pass null if you want one generated 152 * @param int $len The length of the salt 153 * @param bool $cut Apply length restriction to existing salt? 154 */ 155 public function init_salt(&$salt, $len = 32, $cut = true) 156 { 157 if (is_null($salt)) { 158 $salt = $this->gen_salt($len); 159 $cut = true; // for new hashes we alway apply length restriction 160 } 161 if (strlen($salt) > $len && $cut) $salt = substr($salt, 0, $len); 162 } 163 164 // Password hashing methods follow below 165 166 /** 167 * Password hashing method 'smd5' 168 * 169 * Uses salted MD5 hashs. Salt is 8 bytes long. 170 * 171 * The same mechanism is used by Apache's 'apr1' method. This will 172 * fallback to a implementation in pure PHP if MD5 support is not 173 * available in crypt() 174 * 175 * @author Andreas Gohr <andi@splitbrain.org> 176 * @author <mikey_nich at hotmail dot com> 177 * @link http://php.net/manual/en/function.crypt.php#73619 178 * 179 * @param string $clear The clear text to hash 180 * @param string $salt The salt to use, null for random 181 * @return string Hashed password 182 */ 183 public function hash_smd5($clear, $salt = null) 184 { 185 $this->init_salt($salt, 8); 186 187 if (defined('CRYPT_MD5') && CRYPT_MD5 && $salt !== '') { 188 return crypt($clear, '$1$' . $salt . '$'); 189 } else { 190 // Fall back to PHP-only implementation 191 return $this->hash_apr1($clear, $salt, '1'); 192 } 193 } 194 195 /** 196 * Password hashing method 'lsmd5' 197 * 198 * Uses salted MD5 hashs. Salt is 8 bytes long. 199 * 200 * This is the format used by LDAP. 201 * 202 * @param string $clear The clear text to hash 203 * @param string $salt The salt to use, null for random 204 * @return string Hashed password 205 */ 206 public function hash_lsmd5($clear, $salt = null) 207 { 208 $this->init_salt($salt, 8); 209 return "{SMD5}" . base64_encode(md5($clear . $salt, true) . $salt); 210 } 211 212 /** 213 * Password hashing method 'apr1' 214 * 215 * Uses salted MD5 hashs. Salt is 8 bytes long. 216 * 217 * This is basically the same as smd1 above, but as used by Apache. 218 * 219 * @author <mikey_nich at hotmail dot com> 220 * @link http://php.net/manual/en/function.crypt.php#73619 221 * 222 * @param string $clear The clear text to hash 223 * @param string $salt The salt to use, null for random 224 * @param string $magic The hash identifier (apr1 or 1) 225 * @return string Hashed password 226 */ 227 public function hash_apr1($clear, $salt = null, $magic = 'apr1') 228 { 229 $this->init_salt($salt, 8); 230 231 $len = strlen($clear); 232 $text = $clear . '$' . $magic . '$' . $salt; 233 $bin = pack("H32", md5($clear . $salt . $clear)); 234 for ($i = $len; $i > 0; $i -= 16) { 235 $text .= substr($bin, 0, min(16, $i)); 236 } 237 for ($i = $len; $i > 0; $i >>= 1) { 238 $text .= ($i & 1) ? chr(0) : $clear[0]; 239 } 240 $bin = pack("H32", md5($text)); 241 for ($i = 0; $i < 1000; $i++) { 242 $new = ($i & 1) ? $clear : $bin; 243 if ($i % 3) $new .= $salt; 244 if ($i % 7) $new .= $clear; 245 $new .= ($i & 1) ? $bin : $clear; 246 $bin = pack("H32", md5($new)); 247 } 248 $tmp = ''; 249 for ($i = 0; $i < 5; $i++) { 250 $k = $i + 6; 251 $j = $i + 12; 252 if ($j == 16) $j = 5; 253 $tmp = $bin[$i] . $bin[$k] . $bin[$j] . $tmp; 254 } 255 $tmp = chr(0) . chr(0) . $bin[11] . $tmp; 256 $tmp = strtr( 257 strrev(substr(base64_encode($tmp), 2)), 258 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", 259 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 260 ); 261 return '$' . $magic . '$' . $salt . '$' . $tmp; 262 } 263 264 /** 265 * Password hashing method 'md5' 266 * 267 * Uses MD5 hashs. 268 * 269 * @param string $clear The clear text to hash 270 * @return string Hashed password 271 */ 272 public function hash_md5($clear) 273 { 274 return md5($clear); 275 } 276 277 /** 278 * Password hashing method 'sha1' 279 * 280 * Uses SHA1 hashs. 281 * 282 * @param string $clear The clear text to hash 283 * @return string Hashed password 284 */ 285 public function hash_sha1($clear) 286 { 287 return sha1($clear); 288 } 289 290 /** 291 * Password hashing method 'ssha' as used by LDAP 292 * 293 * Uses salted SHA1 hashs. Salt is 4 bytes long. 294 * 295 * @param string $clear The clear text to hash 296 * @param string $salt The salt to use, null for random 297 * @return string Hashed password 298 */ 299 public function hash_ssha($clear, $salt = null) 300 { 301 $this->init_salt($salt, 4); 302 return '{SSHA}' . base64_encode(pack("H*", sha1($clear . $salt)) . $salt); 303 } 304 305 /** 306 * Password hashing method 'crypt' 307 * 308 * Uses salted crypt hashs. Salt is 2 bytes long. 309 * 310 * @param string $clear The clear text to hash 311 * @param string $salt The salt to use, null for random 312 * @return string Hashed password 313 */ 314 public function hash_crypt($clear, $salt = null) 315 { 316 $this->init_salt($salt, 2); 317 return crypt($clear, $salt); 318 } 319 320 /** 321 * Password hashing method 'mysql' 322 * 323 * This method was used by old MySQL systems 324 * 325 * @link http://php.net/mysql 326 * @author <soren at byu dot edu> 327 * @param string $clear The clear text to hash 328 * @return string Hashed password 329 */ 330 public function hash_mysql($clear) 331 { 332 $nr = 0x50305735; 333 $nr2 = 0x12345671; 334 $add = 7; 335 $charArr = preg_split("//", $clear); 336 foreach ($charArr as $char) { 337 if (($char == '') || ($char == ' ') || ($char == '\t')) continue; 338 $charVal = ord($char); 339 $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8); 340 $nr2 += ($nr2 << 8) ^ $nr; 341 $add += $charVal; 342 } 343 return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff)); 344 } 345 346 /** 347 * Password hashing method 'my411' 348 * 349 * Uses SHA1 hashs. This method is used by MySQL 4.11 and above 350 * 351 * @param string $clear The clear text to hash 352 * @return string Hashed password 353 */ 354 public function hash_my411($clear) 355 { 356 return '*' . strtoupper(sha1(pack("H*", sha1($clear)))); 357 } 358 359 /** 360 * Password hashing method 'kmd5' 361 * 362 * Uses salted MD5 hashs. 363 * 364 * Salt is 2 bytes long, but stored at position 16, so you need to pass at 365 * least 18 bytes. You can pass the crypted hash as salt. 366 * 367 * @param string $clear The clear text to hash 368 * @param string $salt The salt to use, null for random 369 * @return string Hashed password 370 */ 371 public function hash_kmd5($clear, $salt = null) 372 { 373 $this->init_salt($salt); 374 375 $key = substr($salt, 16, 2); 376 $hash1 = strtolower(md5($key . md5($clear))); 377 $hash2 = substr($hash1, 0, 16) . $key . substr($hash1, 16); 378 return $hash2; 379 } 380 381 /** 382 * Password stretched hashing wrapper. 383 * 384 * Initial hash is repeatedly rehashed with same password. 385 * Any salted hash algorithm supported by PHP hash() can be used. Salt 386 * is 1+8 bytes long, 1st byte is the iteration count when given. For null 387 * salts $compute is used. 388 * 389 * The actual iteration count is 2 to the power of the given count, 390 * maximum is 30 (-> 2^30 = 1_073_741_824). If a higher one is given, 391 * the function throws an exception. 392 * This iteration count is expected to grow with increasing power of 393 * new computers. 394 * 395 * @author Andreas Gohr <andi@splitbrain.org> 396 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net> 397 * @link http://www.openwall.com/phpass/ 398 * 399 * @param string $algo The hash algorithm to be used 400 * @param string $clear The clear text to hash 401 * @param string $salt The salt to use, null for random 402 * @param string $magic The hash identifier (P or H) 403 * @param int $compute The iteration count for new passwords 404 * @throws \Exception 405 * @return string Hashed password 406 */ 407 protected function stretched_hash($algo, $clear, $salt = null, $magic = 'P', $compute = 8) 408 { 409 $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; 410 if (is_null($salt)) { 411 $this->init_salt($salt); 412 $salt = $itoa64[$compute] . $salt; // prefix iteration count 413 } 414 $iterc = $salt[0]; // pos 0 of salt is log2(iteration count) 415 $iter = strpos($itoa64, $iterc); 416 417 if ($iter > 30) { 418 throw new \Exception("Too high iteration count ($iter) in " . 419 self::class . '::' . __FUNCTION__); 420 } 421 422 $iter = 1 << $iter; 423 $salt = substr($salt, 1, 8); 424 425 // iterate 426 $hash = hash($algo, $salt . $clear, true); 427 do { 428 $hash = hash($algo, $hash . $clear, true); 429 } while (--$iter); 430 431 // encode 432 $output = ''; 433 $count = strlen($hash); 434 $i = 0; 435 do { 436 $value = ord($hash[$i++]); 437 $output .= $itoa64[$value & 0x3f]; 438 if ($i < $count) 439 $value |= ord($hash[$i]) << 8; 440 $output .= $itoa64[($value >> 6) & 0x3f]; 441 if ($i++ >= $count) 442 break; 443 if ($i < $count) 444 $value |= ord($hash[$i]) << 16; 445 $output .= $itoa64[($value >> 12) & 0x3f]; 446 if ($i++ >= $count) 447 break; 448 $output .= $itoa64[($value >> 18) & 0x3f]; 449 } while ($i < $count); 450 451 return '$' . $magic . '$' . $iterc . $salt . $output; 452 } 453 454 /** 455 * Password hashing method 'pmd5' 456 * 457 * Repeatedly uses salted MD5 hashs. See stretched_hash() for the 458 * details. 459 * 460 * 461 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net> 462 * @link http://www.openwall.com/phpass/ 463 * @see PassHash::stretched_hash() for the implementation details. 464 * 465 * @param string $clear The clear text to hash 466 * @param string $salt The salt to use, null for random 467 * @param string $magic The hash identifier (P or H) 468 * @param int $compute The iteration count for new passwords 469 * @throws Exception 470 * @return string Hashed password 471 */ 472 public function hash_pmd5($clear, $salt = null, $magic = 'P', $compute = 8) 473 { 474 return $this->stretched_hash('md5', $clear, $salt, $magic, $compute); 475 } 476 477 /** 478 * Password hashing method 'drupal_sha512' 479 * 480 * Implements Drupal salted sha512 hashs. Drupal truncates the hash at 55 481 * characters. See stretched_hash() for the details; 482 * 483 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net> 484 * @link https://api.drupal.org/api/drupal/includes%21password.inc/7.x 485 * @see PassHash::stretched_hash() for the implementation details. 486 * 487 * @param string $clear The clear text to hash 488 * @param string $salt The salt to use, null for random 489 * @param string $magic The hash identifier (S) 490 * @param int $compute The iteration count for new passwords (defautl is drupal 7's) 491 * @throws Exception 492 * @return string Hashed password 493 */ 494 public function hash_drupal_sha512($clear, $salt = null, $magic = 'S', $compute = 15) 495 { 496 return substr($this->stretched_hash('sha512', $clear, $salt, $magic, $compute), 0, 55); 497 } 498 499 /** 500 * Alias for hash_pmd5 501 * 502 * @param string $clear 503 * @param null|string $salt 504 * @param string $magic 505 * @param int $compute 506 * 507 * @return string 508 * @throws \Exception 509 */ 510 public function hash_hmd5($clear, $salt = null, $magic = 'H', $compute = 8) 511 { 512 return $this->hash_pmd5($clear, $salt, $magic, $compute); 513 } 514 515 /** 516 * Password hashing method 'djangosha1' 517 * 518 * Uses salted SHA1 hashs. Salt is 5 bytes long. 519 * This is used by the Django Python framework 520 * 521 * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords 522 * 523 * @param string $clear The clear text to hash 524 * @param string $salt The salt to use, null for random 525 * @return string Hashed password 526 */ 527 public function hash_djangosha1($clear, $salt = null) 528 { 529 $this->init_salt($salt, 5); 530 return 'sha1$' . $salt . '$' . sha1($salt . $clear); 531 } 532 533 /** 534 * Password hashing method 'djangomd5' 535 * 536 * Uses salted MD5 hashs. Salt is 5 bytes long. 537 * This is used by the Django Python framework 538 * 539 * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords 540 * 541 * @param string $clear The clear text to hash 542 * @param string $salt The salt to use, null for random 543 * @return string Hashed password 544 */ 545 public function hash_djangomd5($clear, $salt = null) 546 { 547 $this->init_salt($salt, 5); 548 return 'md5$' . $salt . '$' . md5($salt . $clear); 549 } 550 551 /** 552 * Password hashing method 'seafilepbkdf2' 553 * 554 * An algorithm and iteration count should be given in the opts array. 555 * 556 * Hash algorithm is the string that is in the password string in seafile 557 * database. It has to be converted to a php algo name. 558 * 559 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net> 560 * @see https://stackoverflow.com/a/23670177 561 * 562 * @param string $clear The clear text to hash 563 * @param string $salt The salt to use, null for random 564 * @param array $opts ('algo' => hash algorithm, 'iter' => iterations) 565 * @return string Hashed password 566 * @throws Exception when PHP is missing support for the method/algo 567 */ 568 public function hash_seafilepbkdf2($clear, $salt = null, $opts = []) 569 { 570 $this->init_salt($salt, 64); 571 if (empty($opts['algo'])) { 572 $prefixalgo = 'SHA256'; 573 } else { 574 $prefixalgo = $opts['algo']; 575 } 576 $algo = strtolower($prefixalgo); 577 if (empty($opts['iter'])) { 578 $iter = 10000; 579 } else { 580 $iter = (int) $opts['iter']; 581 } 582 if (!function_exists('hash_pbkdf2')) { 583 throw new Exception('This PHP installation has no PBKDF2 support'); 584 } 585 if (!in_array($algo, hash_algos())) { 586 throw new Exception("This PHP installation has no $algo support"); 587 } 588 589 $hash = hash_pbkdf2($algo, $clear, hex2bin($salt), $iter, 0); 590 return "PBKDF2$prefixalgo\$$iter\$$salt\$$hash"; 591 } 592 593 /** 594 * Password hashing method 'djangopbkdf2' 595 * 596 * An algorithm and iteration count should be given in the opts array. 597 * Defaults to sha256 and 24000 iterations 598 * 599 * @param string $clear The clear text to hash 600 * @param string $salt The salt to use, null for random 601 * @param array $opts ('algo' => hash algorithm, 'iter' => iterations) 602 * @return string Hashed password 603 * @throws \Exception when PHP is missing support for the method/algo 604 */ 605 public function hash_djangopbkdf2($clear, $salt = null, $opts = []) 606 { 607 $this->init_salt($salt, 12); 608 if (empty($opts['algo'])) { 609 $algo = 'sha256'; 610 } else { 611 $algo = $opts['algo']; 612 } 613 if (empty($opts['iter'])) { 614 $iter = 24000; 615 } else { 616 $iter = (int) $opts['iter']; 617 } 618 if (!function_exists('hash_pbkdf2')) { 619 throw new \Exception('This PHP installation has no PBKDF2 support'); 620 } 621 if (!in_array($algo, hash_algos())) { 622 throw new \Exception("This PHP installation has no $algo support"); 623 } 624 625 $hash = base64_encode(hash_pbkdf2($algo, $clear, $salt, $iter, 0, true)); 626 return "pbkdf2_$algo\$$iter\$$salt\$$hash"; 627 } 628 629 /** 630 * Alias for djangopbkdf2 defaulting to sha256 as hash algorithm 631 * 632 * @param string $clear The clear text to hash 633 * @param string $salt The salt to use, null for random 634 * @param array $opts ('iter' => iterations) 635 * @return string Hashed password 636 * @throws \Exception when PHP is missing support for the method/algo 637 */ 638 public function hash_djangopbkdf2_sha256($clear, $salt = null, $opts = []) 639 { 640 $opts['algo'] = 'sha256'; 641 return $this->hash_djangopbkdf2($clear, $salt, $opts); 642 } 643 644 /** 645 * Alias for djangopbkdf2 defaulting to sha1 as hash algorithm 646 * 647 * @param string $clear The clear text to hash 648 * @param string $salt The salt to use, null for random 649 * @param array $opts ('iter' => iterations) 650 * @return string Hashed password 651 * @throws \Exception when PHP is missing support for the method/algo 652 */ 653 public function hash_djangopbkdf2_sha1($clear, $salt = null, $opts = []) 654 { 655 $opts['algo'] = 'sha1'; 656 return $this->hash_djangopbkdf2($clear, $salt, $opts); 657 } 658 659 /** 660 * Passwordhashing method 'bcrypt' 661 * 662 * Uses a modified blowfish algorithm called eksblowfish 663 * This method works on PHP 5.3+ only and will throw an exception 664 * if the needed crypt support isn't available 665 * 666 * A full hash should be given as salt (starting with $a2$) or this 667 * will break. When no salt is given, the iteration count can be set 668 * through the $compute variable. 669 * 670 * @param string $clear The clear text to hash 671 * @param string $salt The salt to use, null for random 672 * @param int $compute The iteration count (between 4 and 31) 673 * @throws \Exception 674 * @return string Hashed password 675 */ 676 public function hash_bcrypt($clear, $salt = null, $compute = 10) 677 { 678 if (!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH !== 1) { 679 throw new \Exception('This PHP installation has no bcrypt support'); 680 } 681 682 if (is_null($salt)) { 683 if ($compute < 4 || $compute > 31) $compute = 8; 684 $salt = '$2y$' . str_pad($compute, 2, '0', STR_PAD_LEFT) . '$' . 685 $this->gen_salt(22); 686 } 687 688 return crypt($clear, $salt); 689 } 690 691 /** 692 * Password hashing method 'woltlab' 693 * 694 * Woltlab forums use a bcrypt hash with a custom prefix. 695 * 696 * @param $clear 697 * @param $salt 698 * @return string 699 * @throws \Exception 700 */ 701 public function hash_woltlab($clear, $salt = null) 702 { 703 return 'Bcrypt:' . $this->hash_bcrypt($clear, $salt); 704 } 705 706 /** 707 * Password hashing method SHA-2 708 * 709 * This is only supported on PHP 5.3.2 or higher and will throw an exception if 710 * the needed crypt support is not available 711 * 712 * Uses: 713 * - SHA-2 with 256-bit output for prefix $5$ 714 * - SHA-2 with 512-bit output for prefix $6$ (default) 715 * 716 * @param string $clear The clear text to hash 717 * @param string $salt The salt to use, null for random 718 * @param array $opts ('rounds' => rounds for sha256/sha512, 'prefix' => selected method from SHA-2 family) 719 * @return string Hashed password 720 * @throws \Exception 721 */ 722 public function hash_sha2($clear, $salt = null, $opts = []) 723 { 724 if (empty($opts['prefix'])) { 725 $prefix = '6'; 726 } else { 727 $prefix = $opts['prefix']; 728 } 729 if (empty($opts['rounds'])) { 730 $rounds = null; 731 } else { 732 $rounds = $opts['rounds']; 733 } 734 if ($prefix == '5' && (!defined('CRYPT_SHA256') || CRYPT_SHA256 !== 1)) { 735 throw new \Exception('This PHP installation has no SHA256 support'); 736 } 737 if ($prefix == '6' && (!defined('CRYPT_SHA512') || CRYPT_SHA512 !== 1)) { 738 throw new \Exception('This PHP installation has no SHA512 support'); 739 } 740 $this->init_salt($salt, 8, false); 741 if (empty($rounds)) { 742 return crypt($clear, '$' . $prefix . '$' . $salt . '$'); 743 } else { 744 return crypt($clear, '$' . $prefix . '$' . $rounds . '$' . $salt . '$'); 745 } 746 } 747 748 /** @see sha2 */ 749 public function hash_sha512($clear, $salt = null, $opts = []) 750 { 751 $opts['prefix'] = 6; 752 return $this->hash_sha2($clear, $salt, $opts); 753 } 754 755 /** @see sha2 */ 756 public function hash_sha256($clear, $salt = null, $opts = []) 757 { 758 $opts['prefix'] = 5; 759 return $this->hash_sha2($clear, $salt, $opts); 760 } 761 762 /** 763 * Password hashing method 'mediawiki' 764 * 765 * Uses salted MD5, this is referred to as Method B in MediaWiki docs. Unsalted md5 766 * method 'A' is not supported. 767 * 768 * @link http://www.mediawiki.org/wiki/Manual_talk:User_table#user_password_column 769 * 770 * @param string $clear The clear text to hash 771 * @param string $salt The salt to use, null for random 772 * @return string Hashed password 773 */ 774 public function hash_mediawiki($clear, $salt = null) 775 { 776 $this->init_salt($salt, 8, false); 777 return ':B:' . $salt . ':' . md5($salt . '-' . md5($clear)); 778 } 779 780 781 /** 782 * Password hashing method 'argon2i' 783 * 784 * Uses php's own password_hash function to create argon2i password hash 785 * Default Cost and thread options are used for now. 786 * 787 * @link https://www.php.net/manual/de/function.password-hash.php 788 * 789 * @param string $clear The clear text to hash 790 * @return string Hashed password 791 */ 792 public function hash_argon2i($clear) 793 { 794 if (!defined('PASSWORD_ARGON2I')) { 795 throw new \Exception('This PHP installation has no ARGON2I support'); 796 } 797 return password_hash($clear, PASSWORD_ARGON2I); 798 } 799 800 /** 801 * Password hashing method 'argon2id' 802 * 803 * Uses php's own password_hash function to create argon2id password hash 804 * Default Cost and thread options are used for now. 805 * 806 * @link https://www.php.net/manual/de/function.password-hash.php 807 * 808 * @param string $clear The clear text to hash 809 * @return string Hashed password 810 */ 811 public function hash_argon2id($clear) 812 { 813 if (!defined('PASSWORD_ARGON2ID')) { 814 throw new \Exception('This PHP installation has no ARGON2ID support'); 815 } 816 return password_hash($clear, PASSWORD_ARGON2ID); 817 } 818 819 /** 820 * Wraps around native hash_hmac() or reimplents it 821 * 822 * This is not directly used as password hashing method, and thus isn't callable via the 823 * verify_hash() method. It should be used to create signatures and might be used in other 824 * password hashing methods. 825 * 826 * @see hash_hmac() 827 * @author KC Cloyd 828 * @link http://php.net/manual/en/function.hash-hmac.php#93440 829 * 830 * @param string $algo Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", 831 * etc..) See hash_algos() for a list of supported algorithms. 832 * @param string $data Message to be hashed. 833 * @param string $key Shared secret key used for generating the HMAC variant of the message digest. 834 * @param bool $raw_output When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits. 835 * @return string 836 */ 837 public static function hmac($algo, $data, $key, $raw_output = false) 838 { 839 // use native function if available and not in unit test 840 if (function_exists('hash_hmac') && !defined('SIMPLE_TEST')) { 841 return hash_hmac($algo, $data, $key, $raw_output); 842 } 843 844 $algo = strtolower($algo); 845 $pack = 'H' . strlen($algo('test')); 846 $size = 64; 847 $opad = str_repeat(chr(0x5C), $size); 848 $ipad = str_repeat(chr(0x36), $size); 849 850 if (strlen($key) > $size) { 851 $key = str_pad(pack($pack, $algo($key)), $size, chr(0x00)); 852 } else { 853 $key = str_pad($key, $size, chr(0x00)); 854 } 855 856 for ($i = 0; $i < strlen($key) - 1; $i++) { 857 $ochar = $opad[$i] ^ $key[$i]; 858 $ichar = $ipad[$i] ^ $key[$i]; 859 $opad[$i] = $ochar; 860 $ipad[$i] = $ichar; 861 } 862 863 $output = $algo($opad . pack($pack, $algo($ipad . $data))); 864 865 return ($raw_output) ? pack($pack, $output) : $output; 866 } 867 868 /** 869 * Use a secure random generator 870 * 871 * @param int $min 872 * @param int $max 873 * @return int 874 */ 875 protected function random($min, $max) 876 { 877 try { 878 return random_int($min, $max); 879 } catch (\Exception $e) { 880 // availability of random source is checked elsewhere in DokuWiki 881 // we demote this to an unchecked runtime exception here 882 throw new \RuntimeException($e->getMessage(), $e->getCode(), $e); 883 } 884 } 885} 886