xref: /dokuwiki/inc/PassHash.php (revision 07a871e68609e4cd733faa887b5340da40875db6)
1c3cc6e05SAndreas Gohr<?php
2d4f83172SAndreas Gohr
3c3cc6e05SAndreas Gohr// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
4c3cc6e05SAndreas Gohr
5c3cc6e05SAndreas Gohrnamespace dokuwiki;
6c3cc6e05SAndreas Gohr
7c3cc6e05SAndreas Gohr/**
8c3cc6e05SAndreas Gohr * Password Hashing Class
9c3cc6e05SAndreas Gohr *
10c3cc6e05SAndreas Gohr * This class implements various mechanisms used to hash passwords
11c3cc6e05SAndreas Gohr *
12c3cc6e05SAndreas Gohr * @author  Andreas Gohr <[email protected]>
130f43ea44SSchplurtz le Déboulonné * @author  Schplurtz le Déboulonné <[email protected]>
14c3cc6e05SAndreas Gohr * @license LGPL2
15c3cc6e05SAndreas Gohr */
168c7c53b0SAndreas Gohrclass PassHash
178c7c53b0SAndreas Gohr{
18c3cc6e05SAndreas Gohr    /**
19c3cc6e05SAndreas Gohr     * Verifies a cleartext password against a crypted hash
20c3cc6e05SAndreas Gohr     *
21c3cc6e05SAndreas Gohr     * The method and salt used for the crypted hash is determined automatically,
22c3cc6e05SAndreas Gohr     * then the clear text password is crypted using the same method. If both hashs
23c3cc6e05SAndreas Gohr     * match true is is returned else false
24c3cc6e05SAndreas Gohr     *
25c3cc6e05SAndreas Gohr     * @author  Andreas Gohr <[email protected]>
260f43ea44SSchplurtz le Déboulonné     * @author  Schplurtz le Déboulonné <[email protected]>
27c3cc6e05SAndreas Gohr     *
28c3cc6e05SAndreas Gohr     * @param string $clear Clear-Text password
29c3cc6e05SAndreas Gohr     * @param string $hash  Hash to compare against
30c3cc6e05SAndreas Gohr     * @return  bool
31c3cc6e05SAndreas Gohr     */
32d868eb89SAndreas Gohr    public function verify_hash($clear, $hash)
33d868eb89SAndreas Gohr    {
34c3cc6e05SAndreas Gohr        $method = '';
35c3cc6e05SAndreas Gohr        $salt   = '';
36c3cc6e05SAndreas Gohr        $magic  = '';
37c3cc6e05SAndreas Gohr
38c3cc6e05SAndreas Gohr        //determine the used method and salt
396c16a3a9Sfiwswe        if (str_starts_with($hash, 'U$')) {
400f43ea44SSchplurtz le Déboulonné            // This may be an updated password from user_update_7000(). Such hashes
410f43ea44SSchplurtz le Déboulonné            // have 'U' added as the first character and need an extra md5().
420f43ea44SSchplurtz le Déboulonné            $hash = substr($hash, 1);
430f43ea44SSchplurtz le Déboulonné            $clear = md5($clear);
440f43ea44SSchplurtz le Déboulonné        }
45c3cc6e05SAndreas Gohr        $len = strlen($hash);
46c3cc6e05SAndreas Gohr        if (preg_match('/^\$1\$([^\$]{0,8})\$/', $hash, $m)) {
47c3cc6e05SAndreas Gohr            $method = 'smd5';
48c3cc6e05SAndreas Gohr            $salt   = $m[1];
49c3cc6e05SAndreas Gohr            $magic  = '1';
50c3cc6e05SAndreas Gohr        } elseif (preg_match('/^\$apr1\$([^\$]{0,8})\$/', $hash, $m)) {
51c3cc6e05SAndreas Gohr            $method = 'apr1';
52c3cc6e05SAndreas Gohr            $salt   = $m[1];
53c3cc6e05SAndreas Gohr            $magic  = 'apr1';
540f43ea44SSchplurtz le Déboulonné        } elseif (preg_match('/^\$S\$(.{52})$/', $hash, $m)) {
550f43ea44SSchplurtz le Déboulonné            $method = 'drupal_sha512';
560f43ea44SSchplurtz le Déboulonné            $salt   = $m[1];
570f43ea44SSchplurtz le Déboulonné            $magic  = 'S';
58c3cc6e05SAndreas Gohr        } elseif (preg_match('/^\$P\$(.{31})$/', $hash, $m)) {
59c3cc6e05SAndreas Gohr            $method = 'pmd5';
60c3cc6e05SAndreas Gohr            $salt   = $m[1];
61c3cc6e05SAndreas Gohr            $magic  = 'P';
62c3cc6e05SAndreas Gohr        } elseif (preg_match('/^\$H\$(.{31})$/', $hash, $m)) {
63c3cc6e05SAndreas Gohr            $method = 'pmd5';
64c3cc6e05SAndreas Gohr            $salt = $m[1];
65c3cc6e05SAndreas Gohr            $magic = 'H';
66c3cc6e05SAndreas Gohr        } elseif (preg_match('/^pbkdf2_(\w+?)\$(\d+)\$(.{12})\$/', $hash, $m)) {
67c3cc6e05SAndreas Gohr            $method = 'djangopbkdf2';
6824870174SAndreas Gohr            $magic = ['algo' => $m[1], 'iter' => $m[2]];
69c3cc6e05SAndreas Gohr            $salt = $m[3];
700f43ea44SSchplurtz le Déboulonné        } elseif (preg_match('/^PBKDF2(SHA\d+)\$(\d+)\$([[:xdigit:]]+)\$([[:xdigit:]]+)$/', $hash, $m)) {
710f43ea44SSchplurtz le Déboulonné            $method = 'seafilepbkdf2';
7224870174SAndreas Gohr            $magic = ['algo' => $m[1], 'iter' => $m[2]];
730f43ea44SSchplurtz le Déboulonné            $salt = $m[3];
74c3cc6e05SAndreas Gohr        } elseif (preg_match('/^sha1\$(.{5})\$/', $hash, $m)) {
75c3cc6e05SAndreas Gohr            $method = 'djangosha1';
76c3cc6e05SAndreas Gohr            $salt   = $m[1];
77c3cc6e05SAndreas Gohr        } elseif (preg_match('/^md5\$(.{5})\$/', $hash, $m)) {
78c3cc6e05SAndreas Gohr            $method = 'djangomd5';
79c3cc6e05SAndreas Gohr            $salt   = $m[1];
80dfaf0747SAndreas Gohr        } elseif (preg_match('/^\$2([abxy])\$(.{2})\$/', $hash, $m)) {
81c3cc6e05SAndreas Gohr            $method = 'bcrypt';
82c3cc6e05SAndreas Gohr            $salt = $hash;
83*07a871e6SAndreas Gohr        } elseif (str_starts_with($hash, 'Bcrypt:$2')) {
84*07a871e6SAndreas Gohr            $method = 'woltlab';
85*07a871e6SAndreas Gohr            $salt = substr($hash, 7);
866c16a3a9Sfiwswe        } elseif (str_starts_with($hash, '{SSHA}')) {
87c3cc6e05SAndreas Gohr            $method = 'ssha';
88c3cc6e05SAndreas Gohr            $salt   = substr(base64_decode(substr($hash, 6)), 20);
896c16a3a9Sfiwswe        } elseif (str_starts_with($hash, '{SMD5}')) {
90c3cc6e05SAndreas Gohr            $method = 'lsmd5';
91c3cc6e05SAndreas Gohr            $salt   = substr(base64_decode(substr($hash, 6)), 16);
92c3cc6e05SAndreas Gohr        } elseif (preg_match('/^:B:(.+?):.{32}$/', $hash, $m)) {
93c3cc6e05SAndreas Gohr            $method = 'mediawiki';
94c3cc6e05SAndreas Gohr            $salt   = $m[1];
951c7f6650SJan Baier        } elseif (preg_match('/^\$(5|6)\$(rounds=\d+)?\$?(.+?)\$/', $hash, $m)) {
961c7f6650SJan Baier            $method = 'sha2';
971c7f6650SJan Baier            $salt   = $m[3];
9824870174SAndreas Gohr            $magic  = ['prefix' => $m[1], 'rounds' => $m[2]];
991f993c33SChristian Marg        } elseif (preg_match('/^\$(argon2id?)/', $hash, $m)) {
1001f993c33SChristian Marg            if (!defined('PASSWORD_' . strtoupper($m[1]))) {
1011f993c33SChristian Marg                throw new \Exception('This PHP installation has no ' . strtoupper($m[1]) . ' support');
1021f993c33SChristian Marg            }
1031f993c33SChristian Marg            return password_verify($clear, $hash);
104c3cc6e05SAndreas Gohr        } elseif ($len == 32) {
105c3cc6e05SAndreas Gohr            $method = 'md5';
106c3cc6e05SAndreas Gohr        } elseif ($len == 40) {
107c3cc6e05SAndreas Gohr            $method = 'sha1';
108c3cc6e05SAndreas Gohr        } elseif ($len == 16) {
109c3cc6e05SAndreas Gohr            $method = 'mysql';
110c3cc6e05SAndreas Gohr        } elseif ($len == 41 && $hash[0] == '*') {
111c3cc6e05SAndreas Gohr            $method = 'my411';
112c3cc6e05SAndreas Gohr        } elseif ($len == 34) {
113c3cc6e05SAndreas Gohr            $method = 'kmd5';
114c3cc6e05SAndreas Gohr            $salt   = $hash;
115c3cc6e05SAndreas Gohr        } else {
116c3cc6e05SAndreas Gohr            $method = 'crypt';
117c3cc6e05SAndreas Gohr            $salt   = substr($hash, 0, 2);
118c3cc6e05SAndreas Gohr        }
119c3cc6e05SAndreas Gohr
120c3cc6e05SAndreas Gohr        //crypt and compare
121c3cc6e05SAndreas Gohr        $call = 'hash_' . $method;
122c3cc6e05SAndreas Gohr        $newhash = $this->$call($clear, $salt, $magic);
123c3cc6e05SAndreas Gohr        if (\hash_equals($newhash, $hash)) {
124c3cc6e05SAndreas Gohr            return true;
125c3cc6e05SAndreas Gohr        }
126c3cc6e05SAndreas Gohr        return false;
127c3cc6e05SAndreas Gohr    }
128c3cc6e05SAndreas Gohr
129c3cc6e05SAndreas Gohr    /**
130c3cc6e05SAndreas Gohr     * Create a random salt
131c3cc6e05SAndreas Gohr     *
132c3cc6e05SAndreas Gohr     * @param int $len The length of the salt
133c3cc6e05SAndreas Gohr     * @return string
134c3cc6e05SAndreas Gohr     */
135d868eb89SAndreas Gohr    public function gen_salt($len = 32)
136d868eb89SAndreas Gohr    {
137c3cc6e05SAndreas Gohr        $salt  = '';
138c3cc6e05SAndreas Gohr        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
139c3cc6e05SAndreas Gohr        for ($i = 0; $i < $len; $i++) {
140c3cc6e05SAndreas Gohr            $salt .= $chars[$this->random(0, 61)];
141c3cc6e05SAndreas Gohr        }
142c3cc6e05SAndreas Gohr        return $salt;
143c3cc6e05SAndreas Gohr    }
144c3cc6e05SAndreas Gohr
145c3cc6e05SAndreas Gohr    /**
146c3cc6e05SAndreas Gohr     * Initialize the passed variable with a salt if needed.
147c3cc6e05SAndreas Gohr     *
148c3cc6e05SAndreas Gohr     * If $salt is not null, the value is kept, but the lenght restriction is
149c3cc6e05SAndreas Gohr     * applied (unless, $cut is false).
150c3cc6e05SAndreas Gohr     *
151c3cc6e05SAndreas Gohr     * @param string|null &$salt  The salt, pass null if you want one generated
152c3cc6e05SAndreas Gohr     * @param int          $len   The length of the salt
153c3cc6e05SAndreas Gohr     * @param bool         $cut   Apply length restriction to existing salt?
154c3cc6e05SAndreas Gohr     */
155d868eb89SAndreas Gohr    public function init_salt(&$salt, $len = 32, $cut = true)
156d868eb89SAndreas Gohr    {
157c3cc6e05SAndreas Gohr        if (is_null($salt)) {
158c3cc6e05SAndreas Gohr            $salt = $this->gen_salt($len);
159c3cc6e05SAndreas Gohr            $cut  = true; // for new hashes we alway apply length restriction
160c3cc6e05SAndreas Gohr        }
161c3cc6e05SAndreas Gohr        if (strlen($salt) > $len && $cut) $salt = substr($salt, 0, $len);
162c3cc6e05SAndreas Gohr    }
163c3cc6e05SAndreas Gohr
164c3cc6e05SAndreas Gohr    // Password hashing methods follow below
165c3cc6e05SAndreas Gohr
166c3cc6e05SAndreas Gohr    /**
167c3cc6e05SAndreas Gohr     * Password hashing method 'smd5'
168c3cc6e05SAndreas Gohr     *
169c3cc6e05SAndreas Gohr     * Uses salted MD5 hashs. Salt is 8 bytes long.
170c3cc6e05SAndreas Gohr     *
171c3cc6e05SAndreas Gohr     * The same mechanism is used by Apache's 'apr1' method. This will
172c3cc6e05SAndreas Gohr     * fallback to a implementation in pure PHP if MD5 support is not
173c3cc6e05SAndreas Gohr     * available in crypt()
174c3cc6e05SAndreas Gohr     *
175c3cc6e05SAndreas Gohr     * @author Andreas Gohr <[email protected]>
176c3cc6e05SAndreas Gohr     * @author <mikey_nich at hotmail dot com>
177c3cc6e05SAndreas Gohr     * @link   http://php.net/manual/en/function.crypt.php#73619
178c3cc6e05SAndreas Gohr     *
179c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
180c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
181c3cc6e05SAndreas Gohr     * @return string Hashed password
182c3cc6e05SAndreas Gohr     */
183d868eb89SAndreas Gohr    public function hash_smd5($clear, $salt = null)
184d868eb89SAndreas Gohr    {
185c3cc6e05SAndreas Gohr        $this->init_salt($salt, 8);
186c3cc6e05SAndreas Gohr
187c3cc6e05SAndreas Gohr        if (defined('CRYPT_MD5') && CRYPT_MD5 && $salt !== '') {
188c3cc6e05SAndreas Gohr            return crypt($clear, '$1$' . $salt . '$');
189c3cc6e05SAndreas Gohr        } else {
190c3cc6e05SAndreas Gohr            // Fall back to PHP-only implementation
191c3cc6e05SAndreas Gohr            return $this->hash_apr1($clear, $salt, '1');
192c3cc6e05SAndreas Gohr        }
193c3cc6e05SAndreas Gohr    }
194c3cc6e05SAndreas Gohr
195c3cc6e05SAndreas Gohr    /**
196c3cc6e05SAndreas Gohr     * Password hashing method 'lsmd5'
197c3cc6e05SAndreas Gohr     *
198c3cc6e05SAndreas Gohr     * Uses salted MD5 hashs. Salt is 8 bytes long.
199c3cc6e05SAndreas Gohr     *
200c3cc6e05SAndreas Gohr     * This is the format used by LDAP.
201c3cc6e05SAndreas Gohr     *
202c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
203c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
204c3cc6e05SAndreas Gohr     * @return string Hashed password
205c3cc6e05SAndreas Gohr     */
206d868eb89SAndreas Gohr    public function hash_lsmd5($clear, $salt = null)
207d868eb89SAndreas Gohr    {
208c3cc6e05SAndreas Gohr        $this->init_salt($salt, 8);
209c3cc6e05SAndreas Gohr        return "{SMD5}" . base64_encode(md5($clear . $salt, true) . $salt);
210c3cc6e05SAndreas Gohr    }
211c3cc6e05SAndreas Gohr
212c3cc6e05SAndreas Gohr    /**
213c3cc6e05SAndreas Gohr     * Password hashing method 'apr1'
214c3cc6e05SAndreas Gohr     *
215c3cc6e05SAndreas Gohr     * Uses salted MD5 hashs. Salt is 8 bytes long.
216c3cc6e05SAndreas Gohr     *
217c3cc6e05SAndreas Gohr     * This is basically the same as smd1 above, but as used by Apache.
218c3cc6e05SAndreas Gohr     *
219c3cc6e05SAndreas Gohr     * @author <mikey_nich at hotmail dot com>
220c3cc6e05SAndreas Gohr     * @link   http://php.net/manual/en/function.crypt.php#73619
221c3cc6e05SAndreas Gohr     *
222c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
223c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
224c3cc6e05SAndreas Gohr     * @param string $magic The hash identifier (apr1 or 1)
225c3cc6e05SAndreas Gohr     * @return string Hashed password
226c3cc6e05SAndreas Gohr     */
227d868eb89SAndreas Gohr    public function hash_apr1($clear, $salt = null, $magic = 'apr1')
228d868eb89SAndreas Gohr    {
229c3cc6e05SAndreas Gohr        $this->init_salt($salt, 8);
230c3cc6e05SAndreas Gohr
231c3cc6e05SAndreas Gohr        $len  = strlen($clear);
232c3cc6e05SAndreas Gohr        $text = $clear . '$' . $magic . '$' . $salt;
233c3cc6e05SAndreas Gohr        $bin  = pack("H32", md5($clear . $salt . $clear));
234c3cc6e05SAndreas Gohr        for ($i = $len; $i > 0; $i -= 16) {
235c3cc6e05SAndreas Gohr            $text .= substr($bin, 0, min(16, $i));
236c3cc6e05SAndreas Gohr        }
237c3cc6e05SAndreas Gohr        for ($i = $len; $i > 0; $i >>= 1) {
2382401f18dSSyntaxseed            $text .= ($i & 1) ? chr(0) : $clear[0];
239c3cc6e05SAndreas Gohr        }
240c3cc6e05SAndreas Gohr        $bin = pack("H32", md5($text));
241c3cc6e05SAndreas Gohr        for ($i = 0; $i < 1000; $i++) {
242c3cc6e05SAndreas Gohr            $new = ($i & 1) ? $clear : $bin;
243c3cc6e05SAndreas Gohr            if ($i % 3) $new .= $salt;
244c3cc6e05SAndreas Gohr            if ($i % 7) $new .= $clear;
245c3cc6e05SAndreas Gohr            $new .= ($i & 1) ? $bin : $clear;
246c3cc6e05SAndreas Gohr            $bin = pack("H32", md5($new));
247c3cc6e05SAndreas Gohr        }
248c3cc6e05SAndreas Gohr        $tmp = '';
249c3cc6e05SAndreas Gohr        for ($i = 0; $i < 5; $i++) {
250c3cc6e05SAndreas Gohr            $k = $i + 6;
251c3cc6e05SAndreas Gohr            $j = $i + 12;
252c3cc6e05SAndreas Gohr            if ($j == 16) $j = 5;
253c3cc6e05SAndreas Gohr            $tmp = $bin[$i] . $bin[$k] . $bin[$j] . $tmp;
254c3cc6e05SAndreas Gohr        }
255c3cc6e05SAndreas Gohr        $tmp = chr(0) . chr(0) . $bin[11] . $tmp;
256c3cc6e05SAndreas Gohr        $tmp = strtr(
257c3cc6e05SAndreas Gohr            strrev(substr(base64_encode($tmp), 2)),
258c3cc6e05SAndreas Gohr            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
259c3cc6e05SAndreas Gohr            "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
260c3cc6e05SAndreas Gohr        );
261c3cc6e05SAndreas Gohr        return '$' . $magic . '$' . $salt . '$' . $tmp;
262c3cc6e05SAndreas Gohr    }
263c3cc6e05SAndreas Gohr
264c3cc6e05SAndreas Gohr    /**
265c3cc6e05SAndreas Gohr     * Password hashing method 'md5'
266c3cc6e05SAndreas Gohr     *
267c3cc6e05SAndreas Gohr     * Uses MD5 hashs.
268c3cc6e05SAndreas Gohr     *
269c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
270c3cc6e05SAndreas Gohr     * @return string Hashed password
271c3cc6e05SAndreas Gohr     */
272d868eb89SAndreas Gohr    public function hash_md5($clear)
273d868eb89SAndreas Gohr    {
274c3cc6e05SAndreas Gohr        return md5($clear);
275c3cc6e05SAndreas Gohr    }
276c3cc6e05SAndreas Gohr
277c3cc6e05SAndreas Gohr    /**
278c3cc6e05SAndreas Gohr     * Password hashing method 'sha1'
279c3cc6e05SAndreas Gohr     *
280c3cc6e05SAndreas Gohr     * Uses SHA1 hashs.
281c3cc6e05SAndreas Gohr     *
282c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
283c3cc6e05SAndreas Gohr     * @return string Hashed password
284c3cc6e05SAndreas Gohr     */
285d868eb89SAndreas Gohr    public function hash_sha1($clear)
286d868eb89SAndreas Gohr    {
287c3cc6e05SAndreas Gohr        return sha1($clear);
288c3cc6e05SAndreas Gohr    }
289c3cc6e05SAndreas Gohr
290c3cc6e05SAndreas Gohr    /**
291c3cc6e05SAndreas Gohr     * Password hashing method 'ssha' as used by LDAP
292c3cc6e05SAndreas Gohr     *
293c3cc6e05SAndreas Gohr     * Uses salted SHA1 hashs. Salt is 4 bytes long.
294c3cc6e05SAndreas Gohr     *
295c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
296c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
297c3cc6e05SAndreas Gohr     * @return string Hashed password
298c3cc6e05SAndreas Gohr     */
299d868eb89SAndreas Gohr    public function hash_ssha($clear, $salt = null)
300d868eb89SAndreas Gohr    {
301c3cc6e05SAndreas Gohr        $this->init_salt($salt, 4);
302c3cc6e05SAndreas Gohr        return '{SSHA}' . base64_encode(pack("H*", sha1($clear . $salt)) . $salt);
303c3cc6e05SAndreas Gohr    }
304c3cc6e05SAndreas Gohr
305c3cc6e05SAndreas Gohr    /**
306c3cc6e05SAndreas Gohr     * Password hashing method 'crypt'
307c3cc6e05SAndreas Gohr     *
308c3cc6e05SAndreas Gohr     * Uses salted crypt hashs. Salt is 2 bytes long.
309c3cc6e05SAndreas Gohr     *
310c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
311c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
312c3cc6e05SAndreas Gohr     * @return string Hashed password
313c3cc6e05SAndreas Gohr     */
314d868eb89SAndreas Gohr    public function hash_crypt($clear, $salt = null)
315d868eb89SAndreas Gohr    {
316c3cc6e05SAndreas Gohr        $this->init_salt($salt, 2);
317c3cc6e05SAndreas Gohr        return crypt($clear, $salt);
318c3cc6e05SAndreas Gohr    }
319c3cc6e05SAndreas Gohr
320c3cc6e05SAndreas Gohr    /**
321c3cc6e05SAndreas Gohr     * Password hashing method 'mysql'
322c3cc6e05SAndreas Gohr     *
323c3cc6e05SAndreas Gohr     * This method was used by old MySQL systems
324c3cc6e05SAndreas Gohr     *
325c3cc6e05SAndreas Gohr     * @link   http://php.net/mysql
326c3cc6e05SAndreas Gohr     * @author <soren at byu dot edu>
327c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
328c3cc6e05SAndreas Gohr     * @return string Hashed password
329c3cc6e05SAndreas Gohr     */
330d868eb89SAndreas Gohr    public function hash_mysql($clear)
331d868eb89SAndreas Gohr    {
332c3cc6e05SAndreas Gohr        $nr      = 0x50305735;
333c3cc6e05SAndreas Gohr        $nr2     = 0x12345671;
334c3cc6e05SAndreas Gohr        $add     = 7;
335c3cc6e05SAndreas Gohr        $charArr = preg_split("//", $clear);
336c3cc6e05SAndreas Gohr        foreach ($charArr as $char) {
337c3cc6e05SAndreas Gohr            if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
338c3cc6e05SAndreas Gohr            $charVal = ord($char);
339c3cc6e05SAndreas Gohr            $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
340c3cc6e05SAndreas Gohr            $nr2 += ($nr2 << 8) ^ $nr;
341c3cc6e05SAndreas Gohr            $add += $charVal;
342c3cc6e05SAndreas Gohr        }
343c3cc6e05SAndreas Gohr        return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
344c3cc6e05SAndreas Gohr    }
345c3cc6e05SAndreas Gohr
346c3cc6e05SAndreas Gohr    /**
347c3cc6e05SAndreas Gohr     * Password hashing method 'my411'
348c3cc6e05SAndreas Gohr     *
349c3cc6e05SAndreas Gohr     * Uses SHA1 hashs. This method is used by MySQL 4.11 and above
350c3cc6e05SAndreas Gohr     *
351c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
352c3cc6e05SAndreas Gohr     * @return string Hashed password
353c3cc6e05SAndreas Gohr     */
354d868eb89SAndreas Gohr    public function hash_my411($clear)
355d868eb89SAndreas Gohr    {
356c3cc6e05SAndreas Gohr        return '*' . strtoupper(sha1(pack("H*", sha1($clear))));
357c3cc6e05SAndreas Gohr    }
358c3cc6e05SAndreas Gohr
359c3cc6e05SAndreas Gohr    /**
360c3cc6e05SAndreas Gohr     * Password hashing method 'kmd5'
361c3cc6e05SAndreas Gohr     *
362c3cc6e05SAndreas Gohr     * Uses salted MD5 hashs.
363c3cc6e05SAndreas Gohr     *
364c3cc6e05SAndreas Gohr     * Salt is 2 bytes long, but stored at position 16, so you need to pass at
365c3cc6e05SAndreas Gohr     * least 18 bytes. You can pass the crypted hash as salt.
366c3cc6e05SAndreas Gohr     *
367c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
368c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
369c3cc6e05SAndreas Gohr     * @return string Hashed password
370c3cc6e05SAndreas Gohr     */
371d868eb89SAndreas Gohr    public function hash_kmd5($clear, $salt = null)
372d868eb89SAndreas Gohr    {
373c3cc6e05SAndreas Gohr        $this->init_salt($salt);
374c3cc6e05SAndreas Gohr
375c3cc6e05SAndreas Gohr        $key   = substr($salt, 16, 2);
376c3cc6e05SAndreas Gohr        $hash1 = strtolower(md5($key . md5($clear)));
377c3cc6e05SAndreas Gohr        $hash2 = substr($hash1, 0, 16) . $key . substr($hash1, 16);
378c3cc6e05SAndreas Gohr        return $hash2;
379c3cc6e05SAndreas Gohr    }
380c3cc6e05SAndreas Gohr
381c3cc6e05SAndreas Gohr    /**
3820f43ea44SSchplurtz le Déboulonné     * Password stretched hashing wrapper.
383c3cc6e05SAndreas Gohr     *
3840f43ea44SSchplurtz le Déboulonné     * Initial hash is repeatedly rehashed with same password.
3850f43ea44SSchplurtz le Déboulonné     * Any salted hash algorithm supported by PHP hash() can be used. Salt
3860f43ea44SSchplurtz le Déboulonné     * is 1+8 bytes long, 1st byte is the iteration count when given. For null
3870f43ea44SSchplurtz le Déboulonné     * salts $compute is used.
388c3cc6e05SAndreas Gohr     *
3890f43ea44SSchplurtz le Déboulonné     * The actual iteration count is 2 to the power of the given count,
3900f43ea44SSchplurtz le Déboulonné     * maximum is 30 (-> 2^30 = 1_073_741_824). If a higher one is given,
391b98368ccSSchplurtz le Déboulonné     * the function throws an exception.
3920f43ea44SSchplurtz le Déboulonné     * This iteration count is expected to grow with increasing power of
3930f43ea44SSchplurtz le Déboulonné     * new computers.
394c3cc6e05SAndreas Gohr     *
3950f43ea44SSchplurtz le Déboulonné     * @author  Andreas Gohr <[email protected]>
3960f43ea44SSchplurtz le Déboulonné     * @author  Schplurtz le Déboulonné <[email protected]>
397c3cc6e05SAndreas Gohr     * @link    http://www.openwall.com/phpass/
398c3cc6e05SAndreas Gohr     *
3990f43ea44SSchplurtz le Déboulonné     * @param string $algo    The hash algorithm to be used
400c3cc6e05SAndreas Gohr     * @param string $clear   The clear text to hash
401c3cc6e05SAndreas Gohr     * @param string $salt    The salt to use, null for random
402c3cc6e05SAndreas Gohr     * @param string $magic   The hash identifier (P or H)
403c3cc6e05SAndreas Gohr     * @param int    $compute The iteration count for new passwords
404c3cc6e05SAndreas Gohr     * @throws \Exception
405c3cc6e05SAndreas Gohr     * @return string Hashed password
406c3cc6e05SAndreas Gohr     */
407d868eb89SAndreas Gohr    protected function stretched_hash($algo, $clear, $salt = null, $magic = 'P', $compute = 8)
408d868eb89SAndreas Gohr    {
409c3cc6e05SAndreas Gohr        $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
410c3cc6e05SAndreas Gohr        if (is_null($salt)) {
411c3cc6e05SAndreas Gohr            $this->init_salt($salt);
412c3cc6e05SAndreas Gohr            $salt = $itoa64[$compute] . $salt; // prefix iteration count
413c3cc6e05SAndreas Gohr        }
4140f43ea44SSchplurtz le Déboulonné        $iterc = $salt[0]; // pos 0 of salt is log2(iteration count)
415c3cc6e05SAndreas Gohr        $iter  = strpos($itoa64, $iterc);
416c3cc6e05SAndreas Gohr
417c3cc6e05SAndreas Gohr        if ($iter > 30) {
418c3cc6e05SAndreas Gohr            throw new \Exception("Too high iteration count ($iter) in " .
41924870174SAndreas Gohr                                    self::class . '::' . __FUNCTION__);
420c3cc6e05SAndreas Gohr        }
421c3cc6e05SAndreas Gohr
422c3cc6e05SAndreas Gohr        $iter = 1 << $iter;
423c3cc6e05SAndreas Gohr        $salt = substr($salt, 1, 8);
424c3cc6e05SAndreas Gohr
425c3cc6e05SAndreas Gohr        // iterate
426ed823bcdSAndreas Gohr        $hash = hash($algo, $salt . $clear, true);
427c3cc6e05SAndreas Gohr        do {
4280f43ea44SSchplurtz le Déboulonné            $hash = hash($algo, $hash . $clear, true);
429c3cc6e05SAndreas Gohr        } while (--$iter);
430c3cc6e05SAndreas Gohr
431c3cc6e05SAndreas Gohr        // encode
432c3cc6e05SAndreas Gohr        $output = '';
4330f43ea44SSchplurtz le Déboulonné        $count  = strlen($hash);
434c3cc6e05SAndreas Gohr        $i      = 0;
435c3cc6e05SAndreas Gohr        do {
436c3cc6e05SAndreas Gohr            $value = ord($hash[$i++]);
437c3cc6e05SAndreas Gohr            $output .= $itoa64[$value & 0x3f];
438c3cc6e05SAndreas Gohr            if ($i < $count)
439c3cc6e05SAndreas Gohr                $value |= ord($hash[$i]) << 8;
440c3cc6e05SAndreas Gohr            $output .= $itoa64[($value >> 6) & 0x3f];
441c3cc6e05SAndreas Gohr            if ($i++ >= $count)
442c3cc6e05SAndreas Gohr                break;
443c3cc6e05SAndreas Gohr            if ($i < $count)
444c3cc6e05SAndreas Gohr                $value |= ord($hash[$i]) << 16;
445c3cc6e05SAndreas Gohr            $output .= $itoa64[($value >> 12) & 0x3f];
446c3cc6e05SAndreas Gohr            if ($i++ >= $count)
447c3cc6e05SAndreas Gohr                break;
448c3cc6e05SAndreas Gohr            $output .= $itoa64[($value >> 18) & 0x3f];
449c3cc6e05SAndreas Gohr        } while ($i < $count);
450c3cc6e05SAndreas Gohr
451c3cc6e05SAndreas Gohr        return '$' . $magic . '$' . $iterc . $salt . $output;
452c3cc6e05SAndreas Gohr    }
453c3cc6e05SAndreas Gohr
454c3cc6e05SAndreas Gohr    /**
4550f43ea44SSchplurtz le Déboulonné     * Password hashing method 'pmd5'
4560f43ea44SSchplurtz le Déboulonné     *
4570f43ea44SSchplurtz le Déboulonné     * Repeatedly uses salted MD5 hashs. See stretched_hash() for the
4580f43ea44SSchplurtz le Déboulonné     * details.
4590f43ea44SSchplurtz le Déboulonné     *
4600f43ea44SSchplurtz le Déboulonné     *
4610f43ea44SSchplurtz le Déboulonné     * @author  Schplurtz le Déboulonné <[email protected]>
4620f43ea44SSchplurtz le Déboulonné     * @link    http://www.openwall.com/phpass/
4630f43ea44SSchplurtz le Déboulonné     * @see     PassHash::stretched_hash() for the implementation details.
4640f43ea44SSchplurtz le Déboulonné     *
4650f43ea44SSchplurtz le Déboulonné     * @param string $clear   The clear text to hash
4660f43ea44SSchplurtz le Déboulonné     * @param string $salt    The salt to use, null for random
4670f43ea44SSchplurtz le Déboulonné     * @param string $magic   The hash identifier (P or H)
4680f43ea44SSchplurtz le Déboulonné     * @param int    $compute The iteration count for new passwords
4690f43ea44SSchplurtz le Déboulonné     * @throws Exception
4700f43ea44SSchplurtz le Déboulonné     * @return string Hashed password
4710f43ea44SSchplurtz le Déboulonné     */
472d868eb89SAndreas Gohr    public function hash_pmd5($clear, $salt = null, $magic = 'P', $compute = 8)
473d868eb89SAndreas Gohr    {
4740f43ea44SSchplurtz le Déboulonné        return $this->stretched_hash('md5', $clear, $salt, $magic, $compute);
4750f43ea44SSchplurtz le Déboulonné    }
4760f43ea44SSchplurtz le Déboulonné
4770f43ea44SSchplurtz le Déboulonné    /**
4780f43ea44SSchplurtz le Déboulonné     * Password hashing method 'drupal_sha512'
4790f43ea44SSchplurtz le Déboulonné     *
4800f43ea44SSchplurtz le Déboulonné     * Implements Drupal salted sha512 hashs. Drupal truncates the hash at 55
4810f43ea44SSchplurtz le Déboulonné     * characters. See stretched_hash() for the details;
4820f43ea44SSchplurtz le Déboulonné     *
4830f43ea44SSchplurtz le Déboulonné     * @author  Schplurtz le Déboulonné <[email protected]>
4840f43ea44SSchplurtz le Déboulonné     * @link    https://api.drupal.org/api/drupal/includes%21password.inc/7.x
4850f43ea44SSchplurtz le Déboulonné     * @see     PassHash::stretched_hash() for the implementation details.
4860f43ea44SSchplurtz le Déboulonné     *
4870f43ea44SSchplurtz le Déboulonné     * @param string $clear   The clear text to hash
4880f43ea44SSchplurtz le Déboulonné     * @param string $salt    The salt to use, null for random
4890f43ea44SSchplurtz le Déboulonné     * @param string $magic   The hash identifier (S)
4900f43ea44SSchplurtz le Déboulonné     * @param int    $compute The iteration count for new passwords (defautl is drupal 7's)
4910f43ea44SSchplurtz le Déboulonné     * @throws Exception
4920f43ea44SSchplurtz le Déboulonné     * @return string Hashed password
4930f43ea44SSchplurtz le Déboulonné     */
494d868eb89SAndreas Gohr    public function hash_drupal_sha512($clear, $salt = null, $magic = 'S', $compute = 15)
495d868eb89SAndreas Gohr    {
4960f43ea44SSchplurtz le Déboulonné        return substr($this->stretched_hash('sha512', $clear, $salt, $magic, $compute), 0, 55);
4970f43ea44SSchplurtz le Déboulonné    }
4980f43ea44SSchplurtz le Déboulonné
4990f43ea44SSchplurtz le Déboulonné    /**
500c3cc6e05SAndreas Gohr     * Alias for hash_pmd5
501c3cc6e05SAndreas Gohr     *
502c3cc6e05SAndreas Gohr     * @param string $clear
503c3cc6e05SAndreas Gohr     * @param null|string $salt
504c3cc6e05SAndreas Gohr     * @param string $magic
505c3cc6e05SAndreas Gohr     * @param int $compute
506c3cc6e05SAndreas Gohr     *
507c3cc6e05SAndreas Gohr     * @return string
508c3cc6e05SAndreas Gohr     * @throws \Exception
509c3cc6e05SAndreas Gohr     */
510d868eb89SAndreas Gohr    public function hash_hmd5($clear, $salt = null, $magic = 'H', $compute = 8)
511d868eb89SAndreas Gohr    {
512c3cc6e05SAndreas Gohr        return $this->hash_pmd5($clear, $salt, $magic, $compute);
513c3cc6e05SAndreas Gohr    }
514c3cc6e05SAndreas Gohr
515c3cc6e05SAndreas Gohr    /**
516c3cc6e05SAndreas Gohr     * Password hashing method 'djangosha1'
517c3cc6e05SAndreas Gohr     *
518c3cc6e05SAndreas Gohr     * Uses salted SHA1 hashs. Salt is 5 bytes long.
519c3cc6e05SAndreas Gohr     * This is used by the Django Python framework
520c3cc6e05SAndreas Gohr     *
521c3cc6e05SAndreas Gohr     * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords
522c3cc6e05SAndreas Gohr     *
523c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
524c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
525c3cc6e05SAndreas Gohr     * @return string Hashed password
526c3cc6e05SAndreas Gohr     */
527d868eb89SAndreas Gohr    public function hash_djangosha1($clear, $salt = null)
528d868eb89SAndreas Gohr    {
529c3cc6e05SAndreas Gohr        $this->init_salt($salt, 5);
530c3cc6e05SAndreas Gohr        return 'sha1$' . $salt . '$' . sha1($salt . $clear);
531c3cc6e05SAndreas Gohr    }
532c3cc6e05SAndreas Gohr
533c3cc6e05SAndreas Gohr    /**
534c3cc6e05SAndreas Gohr     * Password hashing method 'djangomd5'
535c3cc6e05SAndreas Gohr     *
536c3cc6e05SAndreas Gohr     * Uses salted MD5 hashs. Salt is 5 bytes long.
537c3cc6e05SAndreas Gohr     * This is used by the Django Python framework
538c3cc6e05SAndreas Gohr     *
539c3cc6e05SAndreas Gohr     * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords
540c3cc6e05SAndreas Gohr     *
541c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
542c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
543c3cc6e05SAndreas Gohr     * @return string Hashed password
544c3cc6e05SAndreas Gohr     */
545d868eb89SAndreas Gohr    public function hash_djangomd5($clear, $salt = null)
546d868eb89SAndreas Gohr    {
547c3cc6e05SAndreas Gohr        $this->init_salt($salt, 5);
548c3cc6e05SAndreas Gohr        return 'md5$' . $salt . '$' . md5($salt . $clear);
549c3cc6e05SAndreas Gohr    }
550c3cc6e05SAndreas Gohr
551c3cc6e05SAndreas Gohr    /**
5520f43ea44SSchplurtz le Déboulonné     * Password hashing method 'seafilepbkdf2'
5530f43ea44SSchplurtz le Déboulonné     *
5540f43ea44SSchplurtz le Déboulonné     * An algorithm and iteration count should be given in the opts array.
5550f43ea44SSchplurtz le Déboulonné     *
5560f43ea44SSchplurtz le Déboulonné     * Hash algorithm is the string that is in the password string in seafile
5570f43ea44SSchplurtz le Déboulonné     * database. It has to be converted to a php algo name.
5580f43ea44SSchplurtz le Déboulonné     *
5590f43ea44SSchplurtz le Déboulonné     * @author Schplurtz le Déboulonné <[email protected]>
5600f43ea44SSchplurtz le Déboulonné     * @see https://stackoverflow.com/a/23670177
5610f43ea44SSchplurtz le Déboulonné     *
5620f43ea44SSchplurtz le Déboulonné     * @param string $clear The clear text to hash
5630f43ea44SSchplurtz le Déboulonné     * @param string $salt  The salt to use, null for random
5640f43ea44SSchplurtz le Déboulonné     * @param array $opts ('algo' => hash algorithm, 'iter' => iterations)
5650f43ea44SSchplurtz le Déboulonné     * @return string Hashed password
5660f43ea44SSchplurtz le Déboulonné     * @throws Exception when PHP is missing support for the method/algo
5670f43ea44SSchplurtz le Déboulonné     */
568d868eb89SAndreas Gohr    public function hash_seafilepbkdf2($clear, $salt = null, $opts = [])
569d868eb89SAndreas Gohr    {
5700f43ea44SSchplurtz le Déboulonné        $this->init_salt($salt, 64);
5710f43ea44SSchplurtz le Déboulonné        if (empty($opts['algo'])) {
5720f43ea44SSchplurtz le Déboulonné            $prefixalgo = 'SHA256';
5730f43ea44SSchplurtz le Déboulonné        } else {
5740f43ea44SSchplurtz le Déboulonné            $prefixalgo = $opts['algo'];
5750f43ea44SSchplurtz le Déboulonné        }
5760f43ea44SSchplurtz le Déboulonné        $algo = strtolower($prefixalgo);
5770f43ea44SSchplurtz le Déboulonné        if (empty($opts['iter'])) {
5780f43ea44SSchplurtz le Déboulonné            $iter = 10000;
5790f43ea44SSchplurtz le Déboulonné        } else {
5800f43ea44SSchplurtz le Déboulonné            $iter = (int) $opts['iter'];
5810f43ea44SSchplurtz le Déboulonné        }
5820f43ea44SSchplurtz le Déboulonné        if (!function_exists('hash_pbkdf2')) {
5830f43ea44SSchplurtz le Déboulonné            throw new Exception('This PHP installation has no PBKDF2 support');
5840f43ea44SSchplurtz le Déboulonné        }
5850f43ea44SSchplurtz le Déboulonné        if (!in_array($algo, hash_algos())) {
5860f43ea44SSchplurtz le Déboulonné            throw new Exception("This PHP installation has no $algo support");
5870f43ea44SSchplurtz le Déboulonné        }
5880f43ea44SSchplurtz le Déboulonné
5890f43ea44SSchplurtz le Déboulonné        $hash = hash_pbkdf2($algo, $clear, hex2bin($salt), $iter, 0);
5900f43ea44SSchplurtz le Déboulonné        return "PBKDF2$prefixalgo\$$iter\$$salt\$$hash";
5910f43ea44SSchplurtz le Déboulonné    }
5920f43ea44SSchplurtz le Déboulonné
5930f43ea44SSchplurtz le Déboulonné    /**
594c3cc6e05SAndreas Gohr     * Password hashing method 'djangopbkdf2'
595c3cc6e05SAndreas Gohr     *
596c3cc6e05SAndreas Gohr     * An algorithm and iteration count should be given in the opts array.
597c3cc6e05SAndreas Gohr     * Defaults to sha256 and 24000 iterations
598c3cc6e05SAndreas Gohr     *
599c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
600c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
601c3cc6e05SAndreas Gohr     * @param array $opts ('algo' => hash algorithm, 'iter' => iterations)
602c3cc6e05SAndreas Gohr     * @return string Hashed password
603c3cc6e05SAndreas Gohr     * @throws \Exception when PHP is missing support for the method/algo
604c3cc6e05SAndreas Gohr     */
605d868eb89SAndreas Gohr    public function hash_djangopbkdf2($clear, $salt = null, $opts = [])
606d868eb89SAndreas Gohr    {
607c3cc6e05SAndreas Gohr        $this->init_salt($salt, 12);
608c3cc6e05SAndreas Gohr        if (empty($opts['algo'])) {
609c3cc6e05SAndreas Gohr            $algo = 'sha256';
610c3cc6e05SAndreas Gohr        } else {
611c3cc6e05SAndreas Gohr            $algo = $opts['algo'];
612c3cc6e05SAndreas Gohr        }
613c3cc6e05SAndreas Gohr        if (empty($opts['iter'])) {
614c3cc6e05SAndreas Gohr            $iter = 24000;
615c3cc6e05SAndreas Gohr        } else {
616c3cc6e05SAndreas Gohr            $iter = (int) $opts['iter'];
617c3cc6e05SAndreas Gohr        }
618c3cc6e05SAndreas Gohr        if (!function_exists('hash_pbkdf2')) {
619c3cc6e05SAndreas Gohr            throw new \Exception('This PHP installation has no PBKDF2 support');
620c3cc6e05SAndreas Gohr        }
621c3cc6e05SAndreas Gohr        if (!in_array($algo, hash_algos())) {
622c3cc6e05SAndreas Gohr            throw new \Exception("This PHP installation has no $algo support");
623c3cc6e05SAndreas Gohr        }
624c3cc6e05SAndreas Gohr
625c3cc6e05SAndreas Gohr        $hash = base64_encode(hash_pbkdf2($algo, $clear, $salt, $iter, 0, true));
626c3cc6e05SAndreas Gohr        return "pbkdf2_$algo\$$iter\$$salt\$$hash";
627c3cc6e05SAndreas Gohr    }
628c3cc6e05SAndreas Gohr
629c3cc6e05SAndreas Gohr    /**
630c3cc6e05SAndreas Gohr     * Alias for djangopbkdf2 defaulting to sha256 as hash algorithm
631c3cc6e05SAndreas Gohr     *
632c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
633c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
634c3cc6e05SAndreas Gohr     * @param array $opts ('iter' => iterations)
635c3cc6e05SAndreas Gohr     * @return string Hashed password
636c3cc6e05SAndreas Gohr     * @throws \Exception when PHP is missing support for the method/algo
637c3cc6e05SAndreas Gohr     */
638d868eb89SAndreas Gohr    public function hash_djangopbkdf2_sha256($clear, $salt = null, $opts = [])
639d868eb89SAndreas Gohr    {
640c3cc6e05SAndreas Gohr        $opts['algo'] = 'sha256';
641c3cc6e05SAndreas Gohr        return $this->hash_djangopbkdf2($clear, $salt, $opts);
642c3cc6e05SAndreas Gohr    }
643c3cc6e05SAndreas Gohr
644c3cc6e05SAndreas Gohr    /**
645c3cc6e05SAndreas Gohr     * Alias for djangopbkdf2 defaulting to sha1 as hash algorithm
646c3cc6e05SAndreas Gohr     *
647c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
648c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
649c3cc6e05SAndreas Gohr     * @param array $opts ('iter' => iterations)
650c3cc6e05SAndreas Gohr     * @return string Hashed password
651c3cc6e05SAndreas Gohr     * @throws \Exception when PHP is missing support for the method/algo
652c3cc6e05SAndreas Gohr     */
653d868eb89SAndreas Gohr    public function hash_djangopbkdf2_sha1($clear, $salt = null, $opts = [])
654d868eb89SAndreas Gohr    {
655c3cc6e05SAndreas Gohr        $opts['algo'] = 'sha1';
656c3cc6e05SAndreas Gohr        return $this->hash_djangopbkdf2($clear, $salt, $opts);
657c3cc6e05SAndreas Gohr    }
658c3cc6e05SAndreas Gohr
659c3cc6e05SAndreas Gohr    /**
660c3cc6e05SAndreas Gohr     * Passwordhashing method 'bcrypt'
661c3cc6e05SAndreas Gohr     *
662c3cc6e05SAndreas Gohr     * Uses a modified blowfish algorithm called eksblowfish
663c3cc6e05SAndreas Gohr     * This method works on PHP 5.3+ only and will throw an exception
664c3cc6e05SAndreas Gohr     * if the needed crypt support isn't available
665c3cc6e05SAndreas Gohr     *
666c3cc6e05SAndreas Gohr     * A full hash should be given as salt (starting with $a2$) or this
667c3cc6e05SAndreas Gohr     * will break. When no salt is given, the iteration count can be set
668c3cc6e05SAndreas Gohr     * through the $compute variable.
669c3cc6e05SAndreas Gohr     *
670c3cc6e05SAndreas Gohr     * @param string $clear   The clear text to hash
671c3cc6e05SAndreas Gohr     * @param string $salt    The salt to use, null for random
672c3cc6e05SAndreas Gohr     * @param int    $compute The iteration count (between 4 and 31)
673c3cc6e05SAndreas Gohr     * @throws \Exception
674c3cc6e05SAndreas Gohr     * @return string Hashed password
675c3cc6e05SAndreas Gohr     */
676d868eb89SAndreas Gohr    public function hash_bcrypt($clear, $salt = null, $compute = 10)
677d868eb89SAndreas Gohr    {
67824870174SAndreas Gohr        if (!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH !== 1) {
679c3cc6e05SAndreas Gohr            throw new \Exception('This PHP installation has no bcrypt support');
680c3cc6e05SAndreas Gohr        }
681c3cc6e05SAndreas Gohr
682c3cc6e05SAndreas Gohr        if (is_null($salt)) {
683c3cc6e05SAndreas Gohr            if ($compute < 4 || $compute > 31) $compute = 8;
684c3cc6e05SAndreas Gohr            $salt = '$2y$' . str_pad($compute, 2, '0', STR_PAD_LEFT) . '$' .
685c3cc6e05SAndreas Gohr                $this->gen_salt(22);
686c3cc6e05SAndreas Gohr        }
687c3cc6e05SAndreas Gohr
688c3cc6e05SAndreas Gohr        return crypt($clear, $salt);
689c3cc6e05SAndreas Gohr    }
690c3cc6e05SAndreas Gohr
691c3cc6e05SAndreas Gohr    /**
692*07a871e6SAndreas Gohr     * Password hashing method 'woltlab'
693*07a871e6SAndreas Gohr     *
694*07a871e6SAndreas Gohr     * Woltlab forums use a bcrypt hash with a custom prefix.
695*07a871e6SAndreas Gohr     *
696*07a871e6SAndreas Gohr     * @param $clear
697*07a871e6SAndreas Gohr     * @param $salt
698*07a871e6SAndreas Gohr     * @return string
699*07a871e6SAndreas Gohr     * @throws \Exception
700*07a871e6SAndreas Gohr     */
701*07a871e6SAndreas Gohr    public function hash_woltlab($clear, $salt = null)
702*07a871e6SAndreas Gohr    {
703*07a871e6SAndreas Gohr        return 'Bcrypt:' . $this->hash_bcrypt($clear, $salt);
704*07a871e6SAndreas Gohr    }
705*07a871e6SAndreas Gohr
706*07a871e6SAndreas Gohr    /**
7071c7f6650SJan Baier     * Password hashing method SHA-2
708c3cc6e05SAndreas Gohr     *
709c3cc6e05SAndreas Gohr     * This is only supported on PHP 5.3.2 or higher and will throw an exception if
710c3cc6e05SAndreas Gohr     * the needed crypt support is not available
711c3cc6e05SAndreas Gohr     *
7121c7f6650SJan Baier     * Uses:
7131c7f6650SJan Baier     *  - SHA-2 with 256-bit output for prefix $5$
7141c7f6650SJan Baier     *  - SHA-2 with 512-bit output for prefix $6$ (default)
7151c7f6650SJan Baier     *
716c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
717c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
7181c7f6650SJan Baier     * @param array $opts ('rounds' => rounds for sha256/sha512, 'prefix' => selected method from SHA-2 family)
719c3cc6e05SAndreas Gohr     * @return string Hashed password
720c3cc6e05SAndreas Gohr     * @throws \Exception
721c3cc6e05SAndreas Gohr     */
722d868eb89SAndreas Gohr    public function hash_sha2($clear, $salt = null, $opts = [])
723d868eb89SAndreas Gohr    {
7241c7f6650SJan Baier        if (empty($opts['prefix'])) {
7251c7f6650SJan Baier            $prefix = '6';
7261c7f6650SJan Baier        } else {
7271c7f6650SJan Baier            $prefix = $opts['prefix'];
7281c7f6650SJan Baier        }
7291c7f6650SJan Baier        if (empty($opts['rounds'])) {
7301c7f6650SJan Baier            $rounds = null;
7311c7f6650SJan Baier        } else {
7321c7f6650SJan Baier            $rounds = $opts['rounds'];
7331c7f6650SJan Baier        }
73424870174SAndreas Gohr        if ($prefix == '5' && (!defined('CRYPT_SHA256') || CRYPT_SHA256 !== 1)) {
7351c7f6650SJan Baier            throw new \Exception('This PHP installation has no SHA256 support');
7361c7f6650SJan Baier        }
73724870174SAndreas Gohr        if ($prefix == '6' && (!defined('CRYPT_SHA512') || CRYPT_SHA512 !== 1)) {
738c3cc6e05SAndreas Gohr            throw new \Exception('This PHP installation has no SHA512 support');
739c3cc6e05SAndreas Gohr        }
740c3cc6e05SAndreas Gohr        $this->init_salt($salt, 8, false);
7411c7f6650SJan Baier        if (empty($rounds)) {
7421c7f6650SJan Baier            return crypt($clear, '$' . $prefix . '$' . $salt . '$');
743c3cc6e05SAndreas Gohr        } else {
7441c7f6650SJan Baier            return crypt($clear, '$' . $prefix . '$' . $rounds . '$' . $salt . '$');
745c3cc6e05SAndreas Gohr        }
746c3cc6e05SAndreas Gohr    }
747c3cc6e05SAndreas Gohr
7480b63e09aSAndreas Gohr    /** @see sha2 */
749d868eb89SAndreas Gohr    public function hash_sha512($clear, $salt = null, $opts = [])
750d868eb89SAndreas Gohr    {
7510b63e09aSAndreas Gohr        $opts['prefix'] = 6;
7520b63e09aSAndreas Gohr        return $this->hash_sha2($clear, $salt, $opts);
7530b63e09aSAndreas Gohr    }
7540b63e09aSAndreas Gohr
7550b63e09aSAndreas Gohr    /** @see sha2 */
756d868eb89SAndreas Gohr    public function hash_sha256($clear, $salt = null, $opts = [])
757d868eb89SAndreas Gohr    {
7580b63e09aSAndreas Gohr        $opts['prefix'] = 5;
7590b63e09aSAndreas Gohr        return $this->hash_sha2($clear, $salt, $opts);
7600b63e09aSAndreas Gohr    }
7610b63e09aSAndreas Gohr
762c3cc6e05SAndreas Gohr    /**
763c3cc6e05SAndreas Gohr     * Password hashing method 'mediawiki'
764c3cc6e05SAndreas Gohr     *
765c3cc6e05SAndreas Gohr     * Uses salted MD5, this is referred to as Method B in MediaWiki docs. Unsalted md5
766c3cc6e05SAndreas Gohr     * method 'A' is not supported.
767c3cc6e05SAndreas Gohr     *
768c3cc6e05SAndreas Gohr     * @link  http://www.mediawiki.org/wiki/Manual_talk:User_table#user_password_column
769c3cc6e05SAndreas Gohr     *
770c3cc6e05SAndreas Gohr     * @param string $clear The clear text to hash
771c3cc6e05SAndreas Gohr     * @param string $salt  The salt to use, null for random
772c3cc6e05SAndreas Gohr     * @return string Hashed password
773c3cc6e05SAndreas Gohr     */
774d868eb89SAndreas Gohr    public function hash_mediawiki($clear, $salt = null)
775d868eb89SAndreas Gohr    {
776c3cc6e05SAndreas Gohr        $this->init_salt($salt, 8, false);
777c3cc6e05SAndreas Gohr        return ':B:' . $salt . ':' . md5($salt . '-' . md5($clear));
778c3cc6e05SAndreas Gohr    }
779c3cc6e05SAndreas Gohr
78038a4a86eSChristian Marg
78138a4a86eSChristian Marg    /**
78238a4a86eSChristian Marg     * Password hashing method 'argon2i'
78338a4a86eSChristian Marg     *
78438a4a86eSChristian Marg     * Uses php's own password_hash function to create argon2i password hash
78538a4a86eSChristian Marg     * Default Cost and thread options are used for now.
78638a4a86eSChristian Marg     *
78738a4a86eSChristian Marg     * @link  https://www.php.net/manual/de/function.password-hash.php
78838a4a86eSChristian Marg     *
78938a4a86eSChristian Marg     * @param string $clear The clear text to hash
79038a4a86eSChristian Marg     * @return string Hashed password
79138a4a86eSChristian Marg     */
792d868eb89SAndreas Gohr    public function hash_argon2i($clear)
793d868eb89SAndreas Gohr    {
79438a4a86eSChristian Marg        if (!defined('PASSWORD_ARGON2I')) {
79538a4a86eSChristian Marg            throw new \Exception('This PHP installation has no ARGON2I support');
79638a4a86eSChristian Marg        }
79738a4a86eSChristian Marg        return password_hash($clear, PASSWORD_ARGON2I);
79838a4a86eSChristian Marg    }
79938a4a86eSChristian Marg
80038a4a86eSChristian Marg    /**
80138a4a86eSChristian Marg     * Password hashing method 'argon2id'
80238a4a86eSChristian Marg     *
80338a4a86eSChristian Marg     * Uses php's own password_hash function to create argon2id password hash
80438a4a86eSChristian Marg     * Default Cost and thread options are used for now.
80538a4a86eSChristian Marg     *
80638a4a86eSChristian Marg     * @link  https://www.php.net/manual/de/function.password-hash.php
80738a4a86eSChristian Marg     *
80838a4a86eSChristian Marg     * @param string $clear The clear text to hash
80938a4a86eSChristian Marg     * @return string Hashed password
81038a4a86eSChristian Marg     */
811d868eb89SAndreas Gohr    public function hash_argon2id($clear)
812d868eb89SAndreas Gohr    {
81338a4a86eSChristian Marg        if (!defined('PASSWORD_ARGON2ID')) {
81438a4a86eSChristian Marg            throw new \Exception('This PHP installation has no ARGON2ID support');
81538a4a86eSChristian Marg        }
81638a4a86eSChristian Marg        return password_hash($clear, PASSWORD_ARGON2ID);
81738a4a86eSChristian Marg    }
81838a4a86eSChristian Marg
819c3cc6e05SAndreas Gohr    /**
820c3cc6e05SAndreas Gohr     * Wraps around native hash_hmac() or reimplents it
821c3cc6e05SAndreas Gohr     *
822c3cc6e05SAndreas Gohr     * This is not directly used as password hashing method, and thus isn't callable via the
823c3cc6e05SAndreas Gohr     * verify_hash() method. It should be used to create signatures and might be used in other
824c3cc6e05SAndreas Gohr     * password hashing methods.
825c3cc6e05SAndreas Gohr     *
826c3cc6e05SAndreas Gohr     * @see hash_hmac()
827c3cc6e05SAndreas Gohr     * @author KC Cloyd
828c3cc6e05SAndreas Gohr     * @link http://php.net/manual/en/function.hash-hmac.php#93440
829c3cc6e05SAndreas Gohr     *
830c3cc6e05SAndreas Gohr     * @param string $algo Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4",
831c3cc6e05SAndreas Gohr     *                     etc..) See hash_algos() for a list of supported algorithms.
832c3cc6e05SAndreas Gohr     * @param string $data Message to be hashed.
833c3cc6e05SAndreas Gohr     * @param string $key  Shared secret key used for generating the HMAC variant of the message digest.
834c3cc6e05SAndreas Gohr     * @param bool $raw_output When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.
835c3cc6e05SAndreas Gohr     * @return string
836c3cc6e05SAndreas Gohr     */
837d868eb89SAndreas Gohr    public static function hmac($algo, $data, $key, $raw_output = false)
838d868eb89SAndreas Gohr    {
839c3cc6e05SAndreas Gohr        // use native function if available and not in unit test
840c3cc6e05SAndreas Gohr        if (function_exists('hash_hmac') && !defined('SIMPLE_TEST')) {
841c3cc6e05SAndreas Gohr            return hash_hmac($algo, $data, $key, $raw_output);
842c3cc6e05SAndreas Gohr        }
843c3cc6e05SAndreas Gohr
844c3cc6e05SAndreas Gohr        $algo = strtolower($algo);
845c3cc6e05SAndreas Gohr        $pack = 'H' . strlen($algo('test'));
846c3cc6e05SAndreas Gohr        $size = 64;
847c3cc6e05SAndreas Gohr        $opad = str_repeat(chr(0x5C), $size);
848c3cc6e05SAndreas Gohr        $ipad = str_repeat(chr(0x36), $size);
849c3cc6e05SAndreas Gohr
850c3cc6e05SAndreas Gohr        if (strlen($key) > $size) {
851c3cc6e05SAndreas Gohr            $key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
852c3cc6e05SAndreas Gohr        } else {
853c3cc6e05SAndreas Gohr            $key = str_pad($key, $size, chr(0x00));
854c3cc6e05SAndreas Gohr        }
855c3cc6e05SAndreas Gohr
856c3cc6e05SAndreas Gohr        for ($i = 0; $i < strlen($key) - 1; $i++) {
857c24231d1SAndreas Gohr            $ochar = $opad[$i] ^ $key[$i];
858c24231d1SAndreas Gohr            $ichar = $ipad[$i] ^ $key[$i];
859c24231d1SAndreas Gohr            $opad[$i] = $ochar;
860c24231d1SAndreas Gohr            $ipad[$i] = $ichar;
861c3cc6e05SAndreas Gohr        }
862c3cc6e05SAndreas Gohr
863c3cc6e05SAndreas Gohr        $output = $algo($opad . pack($pack, $algo($ipad . $data)));
864c3cc6e05SAndreas Gohr
865c3cc6e05SAndreas Gohr        return ($raw_output) ? pack($pack, $output) : $output;
866c3cc6e05SAndreas Gohr    }
867c3cc6e05SAndreas Gohr
868c3cc6e05SAndreas Gohr    /**
869c3cc6e05SAndreas Gohr     * Use a secure random generator
870c3cc6e05SAndreas Gohr     *
871c3cc6e05SAndreas Gohr     * @param int $min
872c3cc6e05SAndreas Gohr     * @param int $max
873c3cc6e05SAndreas Gohr     * @return int
874c3cc6e05SAndreas Gohr     */
875d868eb89SAndreas Gohr    protected function random($min, $max)
876d868eb89SAndreas Gohr    {
877c3cc6e05SAndreas Gohr        try {
878c3cc6e05SAndreas Gohr            return random_int($min, $max);
879c3cc6e05SAndreas Gohr        } catch (\Exception $e) {
880c3cc6e05SAndreas Gohr            // availability of random source is checked elsewhere in DokuWiki
881c3cc6e05SAndreas Gohr            // we demote this to an unchecked runtime exception here
882c3cc6e05SAndreas Gohr            throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);
883c3cc6e05SAndreas Gohr        }
884c3cc6e05SAndreas Gohr    }
885c3cc6e05SAndreas Gohr}
886