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