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