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