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