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