codestyle adjustments: function argument spacing
[dokuwiki.git] / inc / PassHash.php
blobf8896f6ffcb54d2f83ecc429f9012717a2ba0d31
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 {
16 /**
17 * Verifies a cleartext password against a crypted hash
19 * The method and salt used for the crypted hash is determined automatically,
20 * then the clear text password is crypted using the same method. If both hashs
21 * match true is is returned else false
23 * @author Andreas Gohr <andi@splitbrain.org>
24 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
26 * @param string $clear Clear-Text password
27 * @param string $hash Hash to compare against
28 * @return bool
30 public function verify_hash($clear, $hash) {
31 $method = '';
32 $salt = '';
33 $magic = '';
35 //determine the used method and salt
36 if (substr($hash, 0, 2) == 'U$') {
37 // This may be an updated password from user_update_7000(). Such hashes
38 // have 'U' added as the first character and need an extra md5().
39 $hash = substr($hash, 1);
40 $clear = md5($clear);
42 $len = strlen($hash);
43 if(preg_match('/^\$1\$([^\$]{0,8})\$/', $hash, $m)) {
44 $method = 'smd5';
45 $salt = $m[1];
46 $magic = '1';
47 } elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/', $hash, $m)) {
48 $method = 'apr1';
49 $salt = $m[1];
50 $magic = 'apr1';
51 } elseif(preg_match('/^\$S\$(.{52})$/', $hash, $m)) {
52 $method = 'drupal_sha512';
53 $salt = $m[1];
54 $magic = 'S';
55 } elseif(preg_match('/^\$P\$(.{31})$/', $hash, $m)) {
56 $method = 'pmd5';
57 $salt = $m[1];
58 $magic = 'P';
59 } elseif(preg_match('/^\$H\$(.{31})$/', $hash, $m)) {
60 $method = 'pmd5';
61 $salt = $m[1];
62 $magic = 'H';
63 } elseif(preg_match('/^pbkdf2_(\w+?)\$(\d+)\$(.{12})\$/', $hash, $m)) {
64 $method = 'djangopbkdf2';
65 $magic = ['algo' => $m[1], 'iter' => $m[2]];
66 $salt = $m[3];
67 } elseif(preg_match('/^PBKDF2(SHA\d+)\$(\d+)\$([[:xdigit:]]+)\$([[:xdigit:]]+)$/', $hash, $m)) {
68 $method = 'seafilepbkdf2';
69 $magic = ['algo' => $m[1], 'iter' => $m[2]];
70 $salt = $m[3];
71 } elseif(preg_match('/^sha1\$(.{5})\$/', $hash, $m)) {
72 $method = 'djangosha1';
73 $salt = $m[1];
74 } elseif(preg_match('/^md5\$(.{5})\$/', $hash, $m)) {
75 $method = 'djangomd5';
76 $salt = $m[1];
77 } elseif(preg_match('/^\$2(a|y)\$(.{2})\$/', $hash, $m)) {
78 $method = 'bcrypt';
79 $salt = $hash;
80 } elseif(substr($hash, 0, 6) == '{SSHA}') {
81 $method = 'ssha';
82 $salt = substr(base64_decode(substr($hash, 6)), 20);
83 } elseif(substr($hash, 0, 6) == '{SMD5}') {
84 $method = 'lsmd5';
85 $salt = substr(base64_decode(substr($hash, 6)), 16);
86 } elseif(preg_match('/^:B:(.+?):.{32}$/', $hash, $m)) {
87 $method = 'mediawiki';
88 $salt = $m[1];
89 } elseif(preg_match('/^\$(5|6)\$(rounds=\d+)?\$?(.+?)\$/', $hash, $m)) {
90 $method = 'sha2';
91 $salt = $m[3];
92 $magic = ['prefix' => $m[1], 'rounds' => $m[2]];
93 } elseif(preg_match('/^\$(argon2id?)/', $hash, $m)) {
94 if(!defined('PASSWORD_'.strtoupper($m[1]))) {
95 throw new \Exception('This PHP installation has no '.strtoupper($m[1]).' support');
97 return password_verify($clear, $hash);
98 } elseif($len == 32) {
99 $method = 'md5';
100 } elseif($len == 40) {
101 $method = 'sha1';
102 } elseif($len == 16) {
103 $method = 'mysql';
104 } elseif($len == 41 && $hash[0] == '*') {
105 $method = 'my411';
106 } elseif($len == 34) {
107 $method = 'kmd5';
108 $salt = $hash;
109 } else {
110 $method = 'crypt';
111 $salt = substr($hash, 0, 2);
114 //crypt and compare
115 $call = 'hash_'.$method;
116 $newhash = $this->$call($clear, $salt, $magic);
117 if(\hash_equals($newhash, $hash)) {
118 return true;
120 return false;
124 * Create a random salt
126 * @param int $len The length of the salt
127 * @return string
129 public function gen_salt($len = 32) {
130 $salt = '';
131 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
132 for($i = 0; $i < $len; $i++) {
133 $salt .= $chars[$this->random(0, 61)];
135 return $salt;
139 * Initialize the passed variable with a salt if needed.
141 * If $salt is not null, the value is kept, but the lenght restriction is
142 * applied (unless, $cut is false).
144 * @param string|null &$salt The salt, pass null if you want one generated
145 * @param int $len The length of the salt
146 * @param bool $cut Apply length restriction to existing salt?
148 public function init_salt(&$salt, $len = 32, $cut = true) {
149 if(is_null($salt)) {
150 $salt = $this->gen_salt($len);
151 $cut = true; // for new hashes we alway apply length restriction
153 if(strlen($salt) > $len && $cut) $salt = substr($salt, 0, $len);
156 // Password hashing methods follow below
159 * Password hashing method 'smd5'
161 * Uses salted MD5 hashs. Salt is 8 bytes long.
163 * The same mechanism is used by Apache's 'apr1' method. This will
164 * fallback to a implementation in pure PHP if MD5 support is not
165 * available in crypt()
167 * @author Andreas Gohr <andi@splitbrain.org>
168 * @author <mikey_nich at hotmail dot com>
169 * @link http://php.net/manual/en/function.crypt.php#73619
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
175 public function hash_smd5($clear, $salt = null) {
176 $this->init_salt($salt, 8);
178 if(defined('CRYPT_MD5') && CRYPT_MD5 && $salt !== '') {
179 return crypt($clear, '$1$'.$salt.'$');
180 } else {
181 // Fall back to PHP-only implementation
182 return $this->hash_apr1($clear, $salt, '1');
187 * Password hashing method 'lsmd5'
189 * Uses salted MD5 hashs. Salt is 8 bytes long.
191 * This is the format used by LDAP.
193 * @param string $clear The clear text to hash
194 * @param string $salt The salt to use, null for random
195 * @return string Hashed password
197 public function hash_lsmd5($clear, $salt = null) {
198 $this->init_salt($salt, 8);
199 return "{SMD5}".base64_encode(md5($clear.$salt, true).$salt);
203 * Password hashing method 'apr1'
205 * Uses salted MD5 hashs. Salt is 8 bytes long.
207 * This is basically the same as smd1 above, but as used by Apache.
209 * @author <mikey_nich at hotmail dot com>
210 * @link http://php.net/manual/en/function.crypt.php#73619
212 * @param string $clear The clear text to hash
213 * @param string $salt The salt to use, null for random
214 * @param string $magic The hash identifier (apr1 or 1)
215 * @return string Hashed password
217 public function hash_apr1($clear, $salt = null, $magic = 'apr1') {
218 $this->init_salt($salt, 8);
220 $len = strlen($clear);
221 $text = $clear.'$'.$magic.'$'.$salt;
222 $bin = pack("H32", md5($clear.$salt.$clear));
223 for($i = $len; $i > 0; $i -= 16) {
224 $text .= substr($bin, 0, min(16, $i));
226 for($i = $len; $i > 0; $i >>= 1) {
227 $text .= ($i & 1) ? chr(0) : $clear[0];
229 $bin = pack("H32", md5($text));
230 for($i = 0; $i < 1000; $i++) {
231 $new = ($i & 1) ? $clear : $bin;
232 if($i % 3) $new .= $salt;
233 if($i % 7) $new .= $clear;
234 $new .= ($i & 1) ? $bin : $clear;
235 $bin = pack("H32", md5($new));
237 $tmp = '';
238 for($i = 0; $i < 5; $i++) {
239 $k = $i + 6;
240 $j = $i + 12;
241 if($j == 16) $j = 5;
242 $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
244 $tmp = chr(0).chr(0).$bin[11].$tmp;
245 $tmp = strtr(
246 strrev(substr(base64_encode($tmp), 2)),
247 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
248 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
250 return '$'.$magic.'$'.$salt.'$'.$tmp;
254 * Password hashing method 'md5'
256 * Uses MD5 hashs.
258 * @param string $clear The clear text to hash
259 * @return string Hashed password
261 public function hash_md5($clear) {
262 return md5($clear);
266 * Password hashing method 'sha1'
268 * Uses SHA1 hashs.
270 * @param string $clear The clear text to hash
271 * @return string Hashed password
273 public function hash_sha1($clear) {
274 return sha1($clear);
278 * Password hashing method 'ssha' as used by LDAP
280 * Uses salted SHA1 hashs. Salt is 4 bytes long.
282 * @param string $clear The clear text to hash
283 * @param string $salt The salt to use, null for random
284 * @return string Hashed password
286 public function hash_ssha($clear, $salt = null) {
287 $this->init_salt($salt, 4);
288 return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
292 * Password hashing method 'crypt'
294 * Uses salted crypt hashs. Salt is 2 bytes long.
296 * @param string $clear The clear text to hash
297 * @param string $salt The salt to use, null for random
298 * @return string Hashed password
300 public function hash_crypt($clear, $salt = null) {
301 $this->init_salt($salt, 2);
302 return crypt($clear, $salt);
306 * Password hashing method 'mysql'
308 * This method was used by old MySQL systems
310 * @link http://php.net/mysql
311 * @author <soren at byu dot edu>
312 * @param string $clear The clear text to hash
313 * @return string Hashed password
315 public function hash_mysql($clear) {
316 $nr = 0x50305735;
317 $nr2 = 0x12345671;
318 $add = 7;
319 $charArr = preg_split("//", $clear);
320 foreach($charArr as $char) {
321 if(($char == '') || ($char == ' ') || ($char == '\t')) continue;
322 $charVal = ord($char);
323 $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
324 $nr2 += ($nr2 << 8) ^ $nr;
325 $add += $charVal;
327 return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
331 * Password hashing method 'my411'
333 * Uses SHA1 hashs. This method is used by MySQL 4.11 and above
335 * @param string $clear The clear text to hash
336 * @return string Hashed password
338 public function hash_my411($clear) {
339 return '*'.strtoupper(sha1(pack("H*", sha1($clear))));
343 * Password hashing method 'kmd5'
345 * Uses salted MD5 hashs.
347 * Salt is 2 bytes long, but stored at position 16, so you need to pass at
348 * least 18 bytes. You can pass the crypted hash as salt.
350 * @param string $clear The clear text to hash
351 * @param string $salt The salt to use, null for random
352 * @return string Hashed password
354 public function hash_kmd5($clear, $salt = null) {
355 $this->init_salt($salt);
357 $key = substr($salt, 16, 2);
358 $hash1 = strtolower(md5($key.md5($clear)));
359 $hash2 = substr($hash1, 0, 16).$key.substr($hash1, 16);
360 return $hash2;
364 * Password stretched hashing wrapper.
366 * Initial hash is repeatedly rehashed with same password.
367 * Any salted hash algorithm supported by PHP hash() can be used. Salt
368 * is 1+8 bytes long, 1st byte is the iteration count when given. For null
369 * salts $compute is used.
371 * The actual iteration count is 2 to the power of the given count,
372 * maximum is 30 (-> 2^30 = 1_073_741_824). If a higher one is given,
373 * the function throws an exception.
374 * This iteration count is expected to grow with increasing power of
375 * new computers.
377 * @author Andreas Gohr <andi@splitbrain.org>
378 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
379 * @link http://www.openwall.com/phpass/
381 * @param string $algo The hash algorithm to be used
382 * @param string $clear The clear text to hash
383 * @param string $salt The salt to use, null for random
384 * @param string $magic The hash identifier (P or H)
385 * @param int $compute The iteration count for new passwords
386 * @throws \Exception
387 * @return string Hashed password
389 protected function stretched_hash($algo, $clear, $salt = null, $magic = 'P', $compute = 8) {
390 $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
391 if(is_null($salt)) {
392 $this->init_salt($salt);
393 $salt = $itoa64[$compute].$salt; // prefix iteration count
395 $iterc = $salt[0]; // pos 0 of salt is log2(iteration count)
396 $iter = strpos($itoa64, $iterc);
398 if($iter > 30) {
399 throw new \Exception("Too high iteration count ($iter) in ".
400 self::class.'::'.__FUNCTION__);
403 $iter = 1 << $iter;
404 $salt = substr($salt, 1, 8);
406 // iterate
407 $hash = hash($algo, $salt . $clear, TRUE);
408 do {
409 $hash = hash($algo, $hash.$clear, true);
410 } while(--$iter);
412 // encode
413 $output = '';
414 $count = strlen($hash);
415 $i = 0;
416 do {
417 $value = ord($hash[$i++]);
418 $output .= $itoa64[$value & 0x3f];
419 if($i < $count)
420 $value |= ord($hash[$i]) << 8;
421 $output .= $itoa64[($value >> 6) & 0x3f];
422 if($i++ >= $count)
423 break;
424 if($i < $count)
425 $value |= ord($hash[$i]) << 16;
426 $output .= $itoa64[($value >> 12) & 0x3f];
427 if($i++ >= $count)
428 break;
429 $output .= $itoa64[($value >> 18) & 0x3f];
430 } while($i < $count);
432 return '$'.$magic.'$'.$iterc.$salt.$output;
436 * Password hashing method 'pmd5'
438 * Repeatedly uses salted MD5 hashs. See stretched_hash() for the
439 * details.
442 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
443 * @link http://www.openwall.com/phpass/
444 * @see PassHash::stretched_hash() for the implementation details.
446 * @param string $clear The clear text to hash
447 * @param string $salt The salt to use, null for random
448 * @param string $magic The hash identifier (P or H)
449 * @param int $compute The iteration count for new passwords
450 * @throws Exception
451 * @return string Hashed password
453 public function hash_pmd5($clear, $salt = null, $magic = 'P', $compute = 8) {
454 return $this->stretched_hash('md5', $clear, $salt, $magic, $compute);
458 * Password hashing method 'drupal_sha512'
460 * Implements Drupal salted sha512 hashs. Drupal truncates the hash at 55
461 * characters. See stretched_hash() for the details;
463 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
464 * @link https://api.drupal.org/api/drupal/includes%21password.inc/7.x
465 * @see PassHash::stretched_hash() for the implementation details.
467 * @param string $clear The clear text to hash
468 * @param string $salt The salt to use, null for random
469 * @param string $magic The hash identifier (S)
470 * @param int $compute The iteration count for new passwords (defautl is drupal 7's)
471 * @throws Exception
472 * @return string Hashed password
474 public function hash_drupal_sha512($clear, $salt = null, $magic = 'S', $compute = 15) {
475 return substr($this->stretched_hash('sha512', $clear, $salt, $magic, $compute), 0, 55);
479 * Alias for hash_pmd5
481 * @param string $clear
482 * @param null|string $salt
483 * @param string $magic
484 * @param int $compute
486 * @return string
487 * @throws \Exception
489 public function hash_hmd5($clear, $salt = null, $magic = 'H', $compute = 8) {
490 return $this->hash_pmd5($clear, $salt, $magic, $compute);
494 * Password hashing method 'djangosha1'
496 * Uses salted SHA1 hashs. Salt is 5 bytes long.
497 * This is used by the Django Python framework
499 * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords
501 * @param string $clear The clear text to hash
502 * @param string $salt The salt to use, null for random
503 * @return string Hashed password
505 public function hash_djangosha1($clear, $salt = null) {
506 $this->init_salt($salt, 5);
507 return 'sha1$'.$salt.'$'.sha1($salt.$clear);
511 * Password hashing method 'djangomd5'
513 * Uses salted MD5 hashs. Salt is 5 bytes long.
514 * This is used by the Django Python framework
516 * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords
518 * @param string $clear The clear text to hash
519 * @param string $salt The salt to use, null for random
520 * @return string Hashed password
522 public function hash_djangomd5($clear, $salt = null) {
523 $this->init_salt($salt, 5);
524 return 'md5$'.$salt.'$'.md5($salt.$clear);
528 * Password hashing method 'seafilepbkdf2'
530 * An algorithm and iteration count should be given in the opts array.
532 * Hash algorithm is the string that is in the password string in seafile
533 * database. It has to be converted to a php algo name.
535 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
536 * @see https://stackoverflow.com/a/23670177
538 * @param string $clear The clear text to hash
539 * @param string $salt The salt to use, null for random
540 * @param array $opts ('algo' => hash algorithm, 'iter' => iterations)
541 * @return string Hashed password
542 * @throws Exception when PHP is missing support for the method/algo
544 public function hash_seafilepbkdf2($clear, $salt=null, $opts=[]) {
545 $this->init_salt($salt, 64);
546 if(empty($opts['algo'])) {
547 $prefixalgo='SHA256';
548 } else {
549 $prefixalgo=$opts['algo'];
551 $algo = strtolower($prefixalgo);
552 if(empty($opts['iter'])) {
553 $iter = 10000;
554 } else {
555 $iter = (int) $opts['iter'];
557 if(!function_exists('hash_pbkdf2')) {
558 throw new Exception('This PHP installation has no PBKDF2 support');
560 if(!in_array($algo, hash_algos())) {
561 throw new Exception("This PHP installation has no $algo support");
564 $hash = hash_pbkdf2($algo, $clear, hex2bin($salt), $iter, 0);
565 return "PBKDF2$prefixalgo\$$iter\$$salt\$$hash";
569 * Password hashing method 'djangopbkdf2'
571 * An algorithm and iteration count should be given in the opts array.
572 * Defaults to sha256 and 24000 iterations
574 * @param string $clear The clear text to hash
575 * @param string $salt The salt to use, null for random
576 * @param array $opts ('algo' => hash algorithm, 'iter' => iterations)
577 * @return string Hashed password
578 * @throws \Exception when PHP is missing support for the method/algo
580 public function hash_djangopbkdf2($clear, $salt=null, $opts=[]) {
581 $this->init_salt($salt, 12);
582 if(empty($opts['algo'])) {
583 $algo = 'sha256';
584 } else {
585 $algo = $opts['algo'];
587 if(empty($opts['iter'])) {
588 $iter = 24000;
589 } else {
590 $iter = (int) $opts['iter'];
592 if(!function_exists('hash_pbkdf2')) {
593 throw new \Exception('This PHP installation has no PBKDF2 support');
595 if(!in_array($algo, hash_algos())) {
596 throw new \Exception("This PHP installation has no $algo support");
599 $hash = base64_encode(hash_pbkdf2($algo, $clear, $salt, $iter, 0, true));
600 return "pbkdf2_$algo\$$iter\$$salt\$$hash";
604 * Alias for djangopbkdf2 defaulting to sha256 as hash algorithm
606 * @param string $clear The clear text to hash
607 * @param string $salt The salt to use, null for random
608 * @param array $opts ('iter' => iterations)
609 * @return string Hashed password
610 * @throws \Exception when PHP is missing support for the method/algo
612 public function hash_djangopbkdf2_sha256($clear, $salt=null, $opts=[]) {
613 $opts['algo'] = 'sha256';
614 return $this->hash_djangopbkdf2($clear, $salt, $opts);
618 * Alias for djangopbkdf2 defaulting to sha1 as hash algorithm
620 * @param string $clear The clear text to hash
621 * @param string $salt The salt to use, null for random
622 * @param array $opts ('iter' => iterations)
623 * @return string Hashed password
624 * @throws \Exception when PHP is missing support for the method/algo
626 public function hash_djangopbkdf2_sha1($clear, $salt=null, $opts=[]) {
627 $opts['algo'] = 'sha1';
628 return $this->hash_djangopbkdf2($clear, $salt, $opts);
632 * Passwordhashing method 'bcrypt'
634 * Uses a modified blowfish algorithm called eksblowfish
635 * This method works on PHP 5.3+ only and will throw an exception
636 * if the needed crypt support isn't available
638 * A full hash should be given as salt (starting with $a2$) or this
639 * will break. When no salt is given, the iteration count can be set
640 * through the $compute variable.
642 * @param string $clear The clear text to hash
643 * @param string $salt The salt to use, null for random
644 * @param int $compute The iteration count (between 4 and 31)
645 * @throws \Exception
646 * @return string Hashed password
648 public function hash_bcrypt($clear, $salt = null, $compute = 10) {
649 if(!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH !== 1) {
650 throw new \Exception('This PHP installation has no bcrypt support');
653 if(is_null($salt)) {
654 if($compute < 4 || $compute > 31) $compute = 8;
655 $salt = '$2y$'.str_pad($compute, 2, '0', STR_PAD_LEFT).'$'.
656 $this->gen_salt(22);
659 return crypt($clear, $salt);
663 * Password hashing method SHA-2
665 * This is only supported on PHP 5.3.2 or higher and will throw an exception if
666 * the needed crypt support is not available
668 * Uses:
669 * - SHA-2 with 256-bit output for prefix $5$
670 * - SHA-2 with 512-bit output for prefix $6$ (default)
672 * @param string $clear The clear text to hash
673 * @param string $salt The salt to use, null for random
674 * @param array $opts ('rounds' => rounds for sha256/sha512, 'prefix' => selected method from SHA-2 family)
675 * @return string Hashed password
676 * @throws \Exception
678 public function hash_sha2($clear, $salt = null, $opts = []) {
679 if(empty($opts['prefix'])) {
680 $prefix = '6';
681 } else {
682 $prefix = $opts['prefix'];
684 if(empty($opts['rounds'])) {
685 $rounds = null;
686 } else {
687 $rounds = $opts['rounds'];
689 if($prefix == '5' && (!defined('CRYPT_SHA256') || CRYPT_SHA256 !== 1)) {
690 throw new \Exception('This PHP installation has no SHA256 support');
692 if($prefix == '6' && (!defined('CRYPT_SHA512') || CRYPT_SHA512 !== 1)) {
693 throw new \Exception('This PHP installation has no SHA512 support');
695 $this->init_salt($salt, 8, false);
696 if(empty($rounds)) {
697 return crypt($clear, '$'.$prefix.'$'.$salt.'$');
698 }else{
699 return crypt($clear, '$'.$prefix.'$'.$rounds.'$'.$salt.'$');
703 /** @see sha2 */
704 public function hash_sha512($clear, $salt = null, $opts=[]) {
705 $opts['prefix'] = 6;
706 return $this->hash_sha2($clear, $salt, $opts);
709 /** @see sha2 */
710 public function hash_sha256($clear, $salt = null, $opts=[]) {
711 $opts['prefix'] = 5;
712 return $this->hash_sha2($clear, $salt, $opts);
716 * Password hashing method 'mediawiki'
718 * Uses salted MD5, this is referred to as Method B in MediaWiki docs. Unsalted md5
719 * method 'A' is not supported.
721 * @link http://www.mediawiki.org/wiki/Manual_talk:User_table#user_password_column
723 * @param string $clear The clear text to hash
724 * @param string $salt The salt to use, null for random
725 * @return string Hashed password
727 public function hash_mediawiki($clear, $salt = null) {
728 $this->init_salt($salt, 8, false);
729 return ':B:'.$salt.':'.md5($salt.'-'.md5($clear));
734 * Password hashing method 'argon2i'
736 * Uses php's own password_hash function to create argon2i password hash
737 * Default Cost and thread options are used for now.
739 * @link https://www.php.net/manual/de/function.password-hash.php
741 * @param string $clear The clear text to hash
742 * @return string Hashed password
744 public function hash_argon2i($clear) {
745 if(!defined('PASSWORD_ARGON2I')) {
746 throw new \Exception('This PHP installation has no ARGON2I support');
748 return password_hash($clear, PASSWORD_ARGON2I);
752 * Password hashing method 'argon2id'
754 * Uses php's own password_hash function to create argon2id password hash
755 * Default Cost and thread options are used for now.
757 * @link https://www.php.net/manual/de/function.password-hash.php
759 * @param string $clear The clear text to hash
760 * @return string Hashed password
762 public function hash_argon2id($clear) {
763 if(!defined('PASSWORD_ARGON2ID')) {
764 throw new \Exception('This PHP installation has no ARGON2ID support');
766 return password_hash($clear, PASSWORD_ARGON2ID);
770 * Wraps around native hash_hmac() or reimplents it
772 * This is not directly used as password hashing method, and thus isn't callable via the
773 * verify_hash() method. It should be used to create signatures and might be used in other
774 * password hashing methods.
776 * @see hash_hmac()
777 * @author KC Cloyd
778 * @link http://php.net/manual/en/function.hash-hmac.php#93440
780 * @param string $algo Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4",
781 * etc..) See hash_algos() for a list of supported algorithms.
782 * @param string $data Message to be hashed.
783 * @param string $key Shared secret key used for generating the HMAC variant of the message digest.
784 * @param bool $raw_output When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.
785 * @return string
787 public static function hmac($algo, $data, $key, $raw_output = false) {
788 // use native function if available and not in unit test
789 if(function_exists('hash_hmac') && !defined('SIMPLE_TEST')){
790 return hash_hmac($algo, $data, $key, $raw_output);
793 $algo = strtolower($algo);
794 $pack = 'H' . strlen($algo('test'));
795 $size = 64;
796 $opad = str_repeat(chr(0x5C), $size);
797 $ipad = str_repeat(chr(0x36), $size);
799 if(strlen($key) > $size) {
800 $key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
801 } else {
802 $key = str_pad($key, $size, chr(0x00));
805 for($i = 0; $i < strlen($key) - 1; $i++) {
806 $ochar = $opad[$i] ^ $key[$i];
807 $ichar = $ipad[$i] ^ $key[$i];
808 $opad[$i] = $ochar;
809 $ipad[$i] = $ichar;
812 $output = $algo($opad . pack($pack, $algo($ipad . $data)));
814 return ($raw_output) ? pack($pack, $output) : $output;
818 * Use a secure random generator
820 * @param int $min
821 * @param int $max
822 * @return int
824 protected function random($min, $max){
825 try {
826 return random_int($min, $max);
827 } catch (\Exception $e) {
828 // availability of random source is checked elsewhere in DokuWiki
829 // we demote this to an unchecked runtime exception here
830 throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);