code style: indent fixes
[dokuwiki.git] / inc / PassHash.php
blob31d40eb1f60db549e68af1d1b3026fbfc9b637e2
1 <?php
2 // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
4 namespace dokuwiki;
6 /**
7 * Password Hashing Class
9 * This class implements various mechanisms used to hash passwords
11 * @author Andreas Gohr <andi@splitbrain.org>
12 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
13 * @license LGPL2
15 class PassHash
17 /**
18 * Verifies a cleartext password against a crypted hash
20 * The method and salt used for the crypted hash is determined automatically,
21 * then the clear text password is crypted using the same method. If both hashs
22 * match true is is returned else false
24 * @author Andreas Gohr <andi@splitbrain.org>
25 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
27 * @param string $clear Clear-Text password
28 * @param string $hash Hash to compare against
29 * @return bool
31 public function verify_hash($clear, $hash)
33 $method = '';
34 $salt = '';
35 $magic = '';
37 //determine the used method and salt
38 if (substr($hash, 0, 2) == 'U$') {
39 // This may be an updated password from user_update_7000(). Such hashes
40 // have 'U' added as the first character and need an extra md5().
41 $hash = substr($hash, 1);
42 $clear = md5($clear);
44 $len = strlen($hash);
45 if (preg_match('/^\$1\$([^\$]{0,8})\$/', $hash, $m)) {
46 $method = 'smd5';
47 $salt = $m[1];
48 $magic = '1';
49 } elseif (preg_match('/^\$apr1\$([^\$]{0,8})\$/', $hash, $m)) {
50 $method = 'apr1';
51 $salt = $m[1];
52 $magic = 'apr1';
53 } elseif (preg_match('/^\$S\$(.{52})$/', $hash, $m)) {
54 $method = 'drupal_sha512';
55 $salt = $m[1];
56 $magic = 'S';
57 } elseif (preg_match('/^\$P\$(.{31})$/', $hash, $m)) {
58 $method = 'pmd5';
59 $salt = $m[1];
60 $magic = 'P';
61 } elseif (preg_match('/^\$H\$(.{31})$/', $hash, $m)) {
62 $method = 'pmd5';
63 $salt = $m[1];
64 $magic = 'H';
65 } elseif (preg_match('/^pbkdf2_(\w+?)\$(\d+)\$(.{12})\$/', $hash, $m)) {
66 $method = 'djangopbkdf2';
67 $magic = ['algo' => $m[1], 'iter' => $m[2]];
68 $salt = $m[3];
69 } elseif (preg_match('/^PBKDF2(SHA\d+)\$(\d+)\$([[:xdigit:]]+)\$([[:xdigit:]]+)$/', $hash, $m)) {
70 $method = 'seafilepbkdf2';
71 $magic = ['algo' => $m[1], 'iter' => $m[2]];
72 $salt = $m[3];
73 } elseif (preg_match('/^sha1\$(.{5})\$/', $hash, $m)) {
74 $method = 'djangosha1';
75 $salt = $m[1];
76 } elseif (preg_match('/^md5\$(.{5})\$/', $hash, $m)) {
77 $method = 'djangomd5';
78 $salt = $m[1];
79 } elseif (preg_match('/^\$2(a|y)\$(.{2})\$/', $hash, $m)) {
80 $method = 'bcrypt';
81 $salt = $hash;
82 } elseif (substr($hash, 0, 6) == '{SSHA}') {
83 $method = 'ssha';
84 $salt = substr(base64_decode(substr($hash, 6)), 20);
85 } elseif (substr($hash, 0, 6) == '{SMD5}') {
86 $method = 'lsmd5';
87 $salt = substr(base64_decode(substr($hash, 6)), 16);
88 } elseif (preg_match('/^:B:(.+?):.{32}$/', $hash, $m)) {
89 $method = 'mediawiki';
90 $salt = $m[1];
91 } elseif (preg_match('/^\$(5|6)\$(rounds=\d+)?\$?(.+?)\$/', $hash, $m)) {
92 $method = 'sha2';
93 $salt = $m[3];
94 $magic = ['prefix' => $m[1], 'rounds' => $m[2]];
95 } elseif (preg_match('/^\$(argon2id?)/', $hash, $m)) {
96 if (!defined('PASSWORD_'.strtoupper($m[1]))) {
97 throw new \Exception('This PHP installation has no '.strtoupper($m[1]).' support');
99 return password_verify($clear, $hash);
100 } elseif ($len == 32) {
101 $method = 'md5';
102 } elseif ($len == 40) {
103 $method = 'sha1';
104 } elseif ($len == 16) {
105 $method = 'mysql';
106 } elseif ($len == 41 && $hash[0] == '*') {
107 $method = 'my411';
108 } elseif ($len == 34) {
109 $method = 'kmd5';
110 $salt = $hash;
111 } else {
112 $method = 'crypt';
113 $salt = substr($hash, 0, 2);
116 //crypt and compare
117 $call = 'hash_'.$method;
118 $newhash = $this->$call($clear, $salt, $magic);
119 if (\hash_equals($newhash, $hash)) {
120 return true;
122 return false;
126 * Create a random salt
128 * @param int $len The length of the salt
129 * @return string
131 public function gen_salt($len = 32)
133 $salt = '';
134 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
135 for ($i = 0; $i < $len; $i++) {
136 $salt .= $chars[$this->random(0, 61)];
138 return $salt;
142 * Initialize the passed variable with a salt if needed.
144 * If $salt is not null, the value is kept, but the lenght restriction is
145 * applied (unless, $cut is false).
147 * @param string|null &$salt The salt, pass null if you want one generated
148 * @param int $len The length of the salt
149 * @param bool $cut Apply length restriction to existing salt?
151 public function init_salt(&$salt, $len = 32, $cut = true)
153 if (is_null($salt)) {
154 $salt = $this->gen_salt($len);
155 $cut = true; // for new hashes we alway apply length restriction
157 if (strlen($salt) > $len && $cut) $salt = substr($salt, 0, $len);
160 // Password hashing methods follow below
163 * Password hashing method 'smd5'
165 * Uses salted MD5 hashs. Salt is 8 bytes long.
167 * The same mechanism is used by Apache's 'apr1' method. This will
168 * fallback to a implementation in pure PHP if MD5 support is not
169 * available in crypt()
171 * @author Andreas Gohr <andi@splitbrain.org>
172 * @author <mikey_nich at hotmail dot com>
173 * @link http://php.net/manual/en/function.crypt.php#73619
175 * @param string $clear The clear text to hash
176 * @param string $salt The salt to use, null for random
177 * @return string Hashed password
179 public function hash_smd5($clear, $salt = null)
181 $this->init_salt($salt, 8);
183 if (defined('CRYPT_MD5') && CRYPT_MD5 && $salt !== '') {
184 return crypt($clear, '$1$'.$salt.'$');
185 } else {
186 // Fall back to PHP-only implementation
187 return $this->hash_apr1($clear, $salt, '1');
192 * Password hashing method 'lsmd5'
194 * Uses salted MD5 hashs. Salt is 8 bytes long.
196 * This is the format used by LDAP.
198 * @param string $clear The clear text to hash
199 * @param string $salt The salt to use, null for random
200 * @return string Hashed password
202 public function hash_lsmd5($clear, $salt = null)
204 $this->init_salt($salt, 8);
205 return "{SMD5}".base64_encode(md5($clear.$salt, true).$salt);
209 * Password hashing method 'apr1'
211 * Uses salted MD5 hashs. Salt is 8 bytes long.
213 * This is basically the same as smd1 above, but as used by Apache.
215 * @author <mikey_nich at hotmail dot com>
216 * @link http://php.net/manual/en/function.crypt.php#73619
218 * @param string $clear The clear text to hash
219 * @param string $salt The salt to use, null for random
220 * @param string $magic The hash identifier (apr1 or 1)
221 * @return string Hashed password
223 public function hash_apr1($clear, $salt = null, $magic = 'apr1')
225 $this->init_salt($salt, 8);
227 $len = strlen($clear);
228 $text = $clear.'$'.$magic.'$'.$salt;
229 $bin = pack("H32", md5($clear.$salt.$clear));
230 for ($i = $len; $i > 0; $i -= 16) {
231 $text .= substr($bin, 0, min(16, $i));
233 for ($i = $len; $i > 0; $i >>= 1) {
234 $text .= ($i & 1) ? chr(0) : $clear[0];
236 $bin = pack("H32", md5($text));
237 for ($i = 0; $i < 1000; $i++) {
238 $new = ($i & 1) ? $clear : $bin;
239 if ($i % 3) $new .= $salt;
240 if ($i % 7) $new .= $clear;
241 $new .= ($i & 1) ? $bin : $clear;
242 $bin = pack("H32", md5($new));
244 $tmp = '';
245 for ($i = 0; $i < 5; $i++) {
246 $k = $i + 6;
247 $j = $i + 12;
248 if ($j == 16) $j = 5;
249 $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
251 $tmp = chr(0).chr(0).$bin[11].$tmp;
252 $tmp = strtr(
253 strrev(substr(base64_encode($tmp), 2)),
254 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
255 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
257 return '$'.$magic.'$'.$salt.'$'.$tmp;
261 * Password hashing method 'md5'
263 * Uses MD5 hashs.
265 * @param string $clear The clear text to hash
266 * @return string Hashed password
268 public function hash_md5($clear)
270 return md5($clear);
274 * Password hashing method 'sha1'
276 * Uses SHA1 hashs.
278 * @param string $clear The clear text to hash
279 * @return string Hashed password
281 public function hash_sha1($clear)
283 return sha1($clear);
287 * Password hashing method 'ssha' as used by LDAP
289 * Uses salted SHA1 hashs. Salt is 4 bytes long.
291 * @param string $clear The clear text to hash
292 * @param string $salt The salt to use, null for random
293 * @return string Hashed password
295 public function hash_ssha($clear, $salt = null)
297 $this->init_salt($salt, 4);
298 return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
302 * Password hashing method 'crypt'
304 * Uses salted crypt hashs. Salt is 2 bytes long.
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_crypt($clear, $salt = null)
312 $this->init_salt($salt, 2);
313 return crypt($clear, $salt);
317 * Password hashing method 'mysql'
319 * This method was used by old MySQL systems
321 * @link http://php.net/mysql
322 * @author <soren at byu dot edu>
323 * @param string $clear The clear text to hash
324 * @return string Hashed password
326 public function hash_mysql($clear)
328 $nr = 0x50305735;
329 $nr2 = 0x12345671;
330 $add = 7;
331 $charArr = preg_split("//", $clear);
332 foreach ($charArr as $char) {
333 if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
334 $charVal = ord($char);
335 $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
336 $nr2 += ($nr2 << 8) ^ $nr;
337 $add += $charVal;
339 return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
343 * Password hashing method 'my411'
345 * Uses SHA1 hashs. This method is used by MySQL 4.11 and above
347 * @param string $clear The clear text to hash
348 * @return string Hashed password
350 public function hash_my411($clear)
352 return '*'.strtoupper(sha1(pack("H*", sha1($clear))));
356 * Password hashing method 'kmd5'
358 * Uses salted MD5 hashs.
360 * Salt is 2 bytes long, but stored at position 16, so you need to pass at
361 * least 18 bytes. You can pass the crypted hash as salt.
363 * @param string $clear The clear text to hash
364 * @param string $salt The salt to use, null for random
365 * @return string Hashed password
367 public function hash_kmd5($clear, $salt = null)
369 $this->init_salt($salt);
371 $key = substr($salt, 16, 2);
372 $hash1 = strtolower(md5($key.md5($clear)));
373 $hash2 = substr($hash1, 0, 16).$key.substr($hash1, 16);
374 return $hash2;
378 * Password stretched hashing wrapper.
380 * Initial hash is repeatedly rehashed with same password.
381 * Any salted hash algorithm supported by PHP hash() can be used. Salt
382 * is 1+8 bytes long, 1st byte is the iteration count when given. For null
383 * salts $compute is used.
385 * The actual iteration count is 2 to the power of the given count,
386 * maximum is 30 (-> 2^30 = 1_073_741_824). If a higher one is given,
387 * the function throws an exception.
388 * This iteration count is expected to grow with increasing power of
389 * new computers.
391 * @author Andreas Gohr <andi@splitbrain.org>
392 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
393 * @link http://www.openwall.com/phpass/
395 * @param string $algo The hash algorithm to be used
396 * @param string $clear The clear text to hash
397 * @param string $salt The salt to use, null for random
398 * @param string $magic The hash identifier (P or H)
399 * @param int $compute The iteration count for new passwords
400 * @throws \Exception
401 * @return string Hashed password
403 protected function stretched_hash($algo, $clear, $salt = null, $magic = 'P', $compute = 8)
405 $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
406 if (is_null($salt)) {
407 $this->init_salt($salt);
408 $salt = $itoa64[$compute].$salt; // prefix iteration count
410 $iterc = $salt[0]; // pos 0 of salt is log2(iteration count)
411 $iter = strpos($itoa64, $iterc);
413 if ($iter > 30) {
414 throw new \Exception("Too high iteration count ($iter) in ".
415 self::class.'::'.__FUNCTION__);
418 $iter = 1 << $iter;
419 $salt = substr($salt, 1, 8);
421 // iterate
422 $hash = hash($algo, $salt . $clear, true);
423 do {
424 $hash = hash($algo, $hash.$clear, true);
425 } while (--$iter);
427 // encode
428 $output = '';
429 $count = strlen($hash);
430 $i = 0;
431 do {
432 $value = ord($hash[$i++]);
433 $output .= $itoa64[$value & 0x3f];
434 if ($i < $count)
435 $value |= ord($hash[$i]) << 8;
436 $output .= $itoa64[($value >> 6) & 0x3f];
437 if ($i++ >= $count)
438 break;
439 if ($i < $count)
440 $value |= ord($hash[$i]) << 16;
441 $output .= $itoa64[($value >> 12) & 0x3f];
442 if ($i++ >= $count)
443 break;
444 $output .= $itoa64[($value >> 18) & 0x3f];
445 } while ($i < $count);
447 return '$'.$magic.'$'.$iterc.$salt.$output;
451 * Password hashing method 'pmd5'
453 * Repeatedly uses salted MD5 hashs. See stretched_hash() for the
454 * details.
457 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
458 * @link http://www.openwall.com/phpass/
459 * @see PassHash::stretched_hash() for the implementation details.
461 * @param string $clear The clear text to hash
462 * @param string $salt The salt to use, null for random
463 * @param string $magic The hash identifier (P or H)
464 * @param int $compute The iteration count for new passwords
465 * @throws Exception
466 * @return string Hashed password
468 public function hash_pmd5($clear, $salt = null, $magic = 'P', $compute = 8)
470 return $this->stretched_hash('md5', $clear, $salt, $magic, $compute);
474 * Password hashing method 'drupal_sha512'
476 * Implements Drupal salted sha512 hashs. Drupal truncates the hash at 55
477 * characters. See stretched_hash() for the details;
479 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
480 * @link https://api.drupal.org/api/drupal/includes%21password.inc/7.x
481 * @see PassHash::stretched_hash() for the implementation details.
483 * @param string $clear The clear text to hash
484 * @param string $salt The salt to use, null for random
485 * @param string $magic The hash identifier (S)
486 * @param int $compute The iteration count for new passwords (defautl is drupal 7's)
487 * @throws Exception
488 * @return string Hashed password
490 public function hash_drupal_sha512($clear, $salt = null, $magic = 'S', $compute = 15)
492 return substr($this->stretched_hash('sha512', $clear, $salt, $magic, $compute), 0, 55);
496 * Alias for hash_pmd5
498 * @param string $clear
499 * @param null|string $salt
500 * @param string $magic
501 * @param int $compute
503 * @return string
504 * @throws \Exception
506 public function hash_hmd5($clear, $salt = null, $magic = 'H', $compute = 8)
508 return $this->hash_pmd5($clear, $salt, $magic, $compute);
512 * Password hashing method 'djangosha1'
514 * Uses salted SHA1 hashs. Salt is 5 bytes long.
515 * This is used by the Django Python framework
517 * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords
519 * @param string $clear The clear text to hash
520 * @param string $salt The salt to use, null for random
521 * @return string Hashed password
523 public function hash_djangosha1($clear, $salt = null)
525 $this->init_salt($salt, 5);
526 return 'sha1$'.$salt.'$'.sha1($salt.$clear);
530 * Password hashing method 'djangomd5'
532 * Uses salted MD5 hashs. Salt is 5 bytes long.
533 * This is used by the Django Python framework
535 * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords
537 * @param string $clear The clear text to hash
538 * @param string $salt The salt to use, null for random
539 * @return string Hashed password
541 public function hash_djangomd5($clear, $salt = null)
543 $this->init_salt($salt, 5);
544 return 'md5$'.$salt.'$'.md5($salt.$clear);
548 * Password hashing method 'seafilepbkdf2'
550 * An algorithm and iteration count should be given in the opts array.
552 * Hash algorithm is the string that is in the password string in seafile
553 * database. It has to be converted to a php algo name.
555 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
556 * @see https://stackoverflow.com/a/23670177
558 * @param string $clear The clear text to hash
559 * @param string $salt The salt to use, null for random
560 * @param array $opts ('algo' => hash algorithm, 'iter' => iterations)
561 * @return string Hashed password
562 * @throws Exception when PHP is missing support for the method/algo
564 public function hash_seafilepbkdf2($clear, $salt = null, $opts = [])
566 $this->init_salt($salt, 64);
567 if (empty($opts['algo'])) {
568 $prefixalgo='SHA256';
569 } else {
570 $prefixalgo=$opts['algo'];
572 $algo = strtolower($prefixalgo);
573 if (empty($opts['iter'])) {
574 $iter = 10000;
575 } else {
576 $iter = (int) $opts['iter'];
578 if (!function_exists('hash_pbkdf2')) {
579 throw new Exception('This PHP installation has no PBKDF2 support');
581 if (!in_array($algo, hash_algos())) {
582 throw new Exception("This PHP installation has no $algo support");
585 $hash = hash_pbkdf2($algo, $clear, hex2bin($salt), $iter, 0);
586 return "PBKDF2$prefixalgo\$$iter\$$salt\$$hash";
590 * Password hashing method 'djangopbkdf2'
592 * An algorithm and iteration count should be given in the opts array.
593 * Defaults to sha256 and 24000 iterations
595 * @param string $clear The clear text to hash
596 * @param string $salt The salt to use, null for random
597 * @param array $opts ('algo' => hash algorithm, 'iter' => iterations)
598 * @return string Hashed password
599 * @throws \Exception when PHP is missing support for the method/algo
601 public function hash_djangopbkdf2($clear, $salt = null, $opts = [])
603 $this->init_salt($salt, 12);
604 if (empty($opts['algo'])) {
605 $algo = 'sha256';
606 } else {
607 $algo = $opts['algo'];
609 if (empty($opts['iter'])) {
610 $iter = 24000;
611 } else {
612 $iter = (int) $opts['iter'];
614 if (!function_exists('hash_pbkdf2')) {
615 throw new \Exception('This PHP installation has no PBKDF2 support');
617 if (!in_array($algo, hash_algos())) {
618 throw new \Exception("This PHP installation has no $algo support");
621 $hash = base64_encode(hash_pbkdf2($algo, $clear, $salt, $iter, 0, true));
622 return "pbkdf2_$algo\$$iter\$$salt\$$hash";
626 * Alias for djangopbkdf2 defaulting to sha256 as hash algorithm
628 * @param string $clear The clear text to hash
629 * @param string $salt The salt to use, null for random
630 * @param array $opts ('iter' => iterations)
631 * @return string Hashed password
632 * @throws \Exception when PHP is missing support for the method/algo
634 public function hash_djangopbkdf2_sha256($clear, $salt = null, $opts = [])
636 $opts['algo'] = 'sha256';
637 return $this->hash_djangopbkdf2($clear, $salt, $opts);
641 * Alias for djangopbkdf2 defaulting to sha1 as hash algorithm
643 * @param string $clear The clear text to hash
644 * @param string $salt The salt to use, null for random
645 * @param array $opts ('iter' => iterations)
646 * @return string Hashed password
647 * @throws \Exception when PHP is missing support for the method/algo
649 public function hash_djangopbkdf2_sha1($clear, $salt = null, $opts = [])
651 $opts['algo'] = 'sha1';
652 return $this->hash_djangopbkdf2($clear, $salt, $opts);
656 * Passwordhashing method 'bcrypt'
658 * Uses a modified blowfish algorithm called eksblowfish
659 * This method works on PHP 5.3+ only and will throw an exception
660 * if the needed crypt support isn't available
662 * A full hash should be given as salt (starting with $a2$) or this
663 * will break. When no salt is given, the iteration count can be set
664 * through the $compute variable.
666 * @param string $clear The clear text to hash
667 * @param string $salt The salt to use, null for random
668 * @param int $compute The iteration count (between 4 and 31)
669 * @throws \Exception
670 * @return string Hashed password
672 public function hash_bcrypt($clear, $salt = null, $compute = 10)
674 if (!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH !== 1) {
675 throw new \Exception('This PHP installation has no bcrypt support');
678 if (is_null($salt)) {
679 if ($compute < 4 || $compute > 31) $compute = 8;
680 $salt = '$2y$'.str_pad($compute, 2, '0', STR_PAD_LEFT).'$'.
681 $this->gen_salt(22);
684 return crypt($clear, $salt);
688 * Password hashing method SHA-2
690 * This is only supported on PHP 5.3.2 or higher and will throw an exception if
691 * the needed crypt support is not available
693 * Uses:
694 * - SHA-2 with 256-bit output for prefix $5$
695 * - SHA-2 with 512-bit output for prefix $6$ (default)
697 * @param string $clear The clear text to hash
698 * @param string $salt The salt to use, null for random
699 * @param array $opts ('rounds' => rounds for sha256/sha512, 'prefix' => selected method from SHA-2 family)
700 * @return string Hashed password
701 * @throws \Exception
703 public function hash_sha2($clear, $salt = null, $opts = [])
705 if (empty($opts['prefix'])) {
706 $prefix = '6';
707 } else {
708 $prefix = $opts['prefix'];
710 if (empty($opts['rounds'])) {
711 $rounds = null;
712 } else {
713 $rounds = $opts['rounds'];
715 if ($prefix == '5' && (!defined('CRYPT_SHA256') || CRYPT_SHA256 !== 1)) {
716 throw new \Exception('This PHP installation has no SHA256 support');
718 if ($prefix == '6' && (!defined('CRYPT_SHA512') || CRYPT_SHA512 !== 1)) {
719 throw new \Exception('This PHP installation has no SHA512 support');
721 $this->init_salt($salt, 8, false);
722 if (empty($rounds)) {
723 return crypt($clear, '$'.$prefix.'$'.$salt.'$');
724 } else {
725 return crypt($clear, '$'.$prefix.'$'.$rounds.'$'.$salt.'$');
729 /** @see sha2 */
730 public function hash_sha512($clear, $salt = null, $opts = [])
732 $opts['prefix'] = 6;
733 return $this->hash_sha2($clear, $salt, $opts);
736 /** @see sha2 */
737 public function hash_sha256($clear, $salt = null, $opts = [])
739 $opts['prefix'] = 5;
740 return $this->hash_sha2($clear, $salt, $opts);
744 * Password hashing method 'mediawiki'
746 * Uses salted MD5, this is referred to as Method B in MediaWiki docs. Unsalted md5
747 * method 'A' is not supported.
749 * @link http://www.mediawiki.org/wiki/Manual_talk:User_table#user_password_column
751 * @param string $clear The clear text to hash
752 * @param string $salt The salt to use, null for random
753 * @return string Hashed password
755 public function hash_mediawiki($clear, $salt = null)
757 $this->init_salt($salt, 8, false);
758 return ':B:'.$salt.':'.md5($salt.'-'.md5($clear));
763 * Password hashing method 'argon2i'
765 * Uses php's own password_hash function to create argon2i password hash
766 * Default Cost and thread options are used for now.
768 * @link https://www.php.net/manual/de/function.password-hash.php
770 * @param string $clear The clear text to hash
771 * @return string Hashed password
773 public function hash_argon2i($clear)
775 if (!defined('PASSWORD_ARGON2I')) {
776 throw new \Exception('This PHP installation has no ARGON2I support');
778 return password_hash($clear, PASSWORD_ARGON2I);
782 * Password hashing method 'argon2id'
784 * Uses php's own password_hash function to create argon2id password hash
785 * Default Cost and thread options are used for now.
787 * @link https://www.php.net/manual/de/function.password-hash.php
789 * @param string $clear The clear text to hash
790 * @return string Hashed password
792 public function hash_argon2id($clear)
794 if (!defined('PASSWORD_ARGON2ID')) {
795 throw new \Exception('This PHP installation has no ARGON2ID support');
797 return password_hash($clear, PASSWORD_ARGON2ID);
801 * Wraps around native hash_hmac() or reimplents it
803 * This is not directly used as password hashing method, and thus isn't callable via the
804 * verify_hash() method. It should be used to create signatures and might be used in other
805 * password hashing methods.
807 * @see hash_hmac()
808 * @author KC Cloyd
809 * @link http://php.net/manual/en/function.hash-hmac.php#93440
811 * @param string $algo Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4",
812 * etc..) See hash_algos() for a list of supported algorithms.
813 * @param string $data Message to be hashed.
814 * @param string $key Shared secret key used for generating the HMAC variant of the message digest.
815 * @param bool $raw_output When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.
816 * @return string
818 public static function hmac($algo, $data, $key, $raw_output = false)
820 // use native function if available and not in unit test
821 if (function_exists('hash_hmac') && !defined('SIMPLE_TEST')) {
822 return hash_hmac($algo, $data, $key, $raw_output);
825 $algo = strtolower($algo);
826 $pack = 'H' . strlen($algo('test'));
827 $size = 64;
828 $opad = str_repeat(chr(0x5C), $size);
829 $ipad = str_repeat(chr(0x36), $size);
831 if (strlen($key) > $size) {
832 $key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
833 } else {
834 $key = str_pad($key, $size, chr(0x00));
837 for ($i = 0; $i < strlen($key) - 1; $i++) {
838 $ochar = $opad[$i] ^ $key[$i];
839 $ichar = $ipad[$i] ^ $key[$i];
840 $opad[$i] = $ochar;
841 $ipad[$i] = $ichar;
844 $output = $algo($opad . pack($pack, $algo($ipad . $data)));
846 return ($raw_output) ? pack($pack, $output) : $output;
850 * Use a secure random generator
852 * @param int $min
853 * @param int $max
854 * @return int
856 protected function random($min, $max)
858 try {
859 return random_int($min, $max);
860 } catch (\Exception $e) {
861 // availability of random source is checked elsewhere in DokuWiki
862 // we demote this to an unchecked runtime exception here
863 throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);