Subversion Repositories php_utils

Rev

Rev 66 | Rev 68 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 66 Rev 67
1
<?php
1
<?php
2
 
2
 
3
/*
3
/*
4
 * ViaThinkSoft Modular Crypt Format 1.0 / vts_password_hash() / vts_password_verify()
4
 * ViaThinkSoft Modular Crypt Format 1.0 / vts_password_hash() / vts_password_verify()
5
 * Copyright 2023 Daniel Marschall, ViaThinkSoft
5
 * Copyright 2023 Daniel Marschall, ViaThinkSoft
6
 * Revision 2023-02-28
6
 * Revision 2023-02-28
7
 *
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
10
 * You may obtain a copy of the License at
11
 *
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
18
 * limitations under the License.
19
 */
19
 */
20
 
20
 
21
/*
21
/*
22
 
22
 
23
The function vts_password_hash() replaces password_hash()
23
The function vts_password_hash() replaces password_hash()
24
and adds the ViaThinkSoft Modular Crypt Format 1.0 hash as well as
24
and adds the ViaThinkSoft Modular Crypt Format 1.0 hash as well as
25
all hashes from password_hash() and crypt().
25
all hashes from password_hash() and crypt().
26
 
26
 
27
The function vts_password_verify() replaces password_verify().
27
The function vts_password_verify() replaces password_verify().
28
 
28
 
29
ViaThinkSoft Modular Crypt Format 1.0 performs a simple hash or HMAC operation.
29
ViaThinkSoft Modular Crypt Format 1.0 performs a simple hash or HMAC operation.
30
No key derivation function or iterations are performed.
30
No key derivation function or iterations are performed.
31
Format:
31
Format:
32
        $1.3.6.1.4.1.37476.3.0.1.1$a=<algo>,m=<mode>$<salt>$<hash>
32
        $1.3.6.1.4.1.37476.3.0.1.1$a=<algo>,m=<mode>$<salt>$<hash>
33
where <algo> is any valid hash algorithm (name scheme of PHP hash_algos() preferred), e.g.
33
where <algo> is any valid hash algorithm (name scheme of PHP hash_algos() preferred), e.g.
34
        sha3-512
34
        sha3-512
35
        sha3-384
35
        sha3-384
36
        sha3-256
36
        sha3-256
37
        sha3-224
37
        sha3-224
38
        sha512
38
        sha512
39
        sha512/256
39
        sha512/256
40
        sha512/224
40
        sha512/224
41
        sha384
41
        sha384
42
        sha256
42
        sha256
43
        sha224
43
        sha224
44
        sha1
44
        sha1
45
        md5
45
        md5
46
Valid <mode> :
46
Valid <mode> :
47
        sp = salt + password
47
        sp = salt + password
48
        ps = password + salt
48
        ps = password + salt
49
        sps = salt + password + salt
49
        sps = salt + password + salt
50
        hmac = HMAC (salt is the key)
50
        hmac = HMAC (salt is the key)
51
        pbkdf2 = PBKDF2 (Additional param i= contains the number of iterations)
51
        pbkdf2 = PBKDF2 (Additional param i= contains the number of iterations)
52
Like most Crypt-hashes, <salt> and <hash> are Radix64 coded
52
Like most Crypt-hashes, <salt> and <hash> are Radix64 coded
53
with alphabet './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' and no padding.
53
with alphabet './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' and no padding.
54
Link to the online specification:
54
Link to the online specification:
55
        https://oidplus.viathinksoft.com/oidplus/?goto=oid%3A1.3.6.1.4.1.37476.3.0.1.1
55
        https://oidplus.viathinksoft.com/oidplus/?goto=oid%3A1.3.6.1.4.1.37476.3.0.1.1
56
Reference implementation in PHP:
56
Reference implementation in PHP:
57
        https://github.com/danielmarschall/php_utils/blob/master/vts_crypt.inc.php
57
        https://github.com/danielmarschall/php_utils/blob/master/vts_crypt.inc.php
58
 
58
 
59
*/
59
*/
60
 
60
 
61
require_once __DIR__ . '/misc_functions.inc.php';
61
require_once __DIR__ . '/misc_functions.inc.php';
62
 
62
 
63
define('OID_MCF_VTS_V1',     '1.3.6.1.4.1.37476.3.0.1.1'); // { iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) 37476 specifications(3) misc(0) modular-crypt-format(1) vts-crypt-v1(1) }
63
define('OID_MCF_VTS_V1',     '1.3.6.1.4.1.37476.3.0.1.1'); // { iso(1) identified-organization(3) dod(6) internet(1) private(4) enterprise(1) 37476 specifications(3) misc(0) modular-crypt-format(1) vts-crypt-v1(1) }
64
 
64
 
65
// Valid algorithms for vts_password_hash():
65
// Valid algorithms for vts_password_hash():
66
define('PASSWORD_STD_DES',   'std_des');       // Algorithm from crypt()
66
define('PASSWORD_STD_DES',   'std_des');       // Algorithm from crypt()
67
define('PASSWORD_EXT_DES',   'ext_des');       // Algorithm from crypt()
67
define('PASSWORD_EXT_DES',   'ext_des');       // Algorithm from crypt()
68
define('PASSWORD_MD5',       'md5');           // Algorithm from crypt()
68
define('PASSWORD_MD5',       'md5');           // Algorithm from crypt()
69
define('PASSWORD_BLOWFISH',  'blowfish');      // Algorithm from crypt()
69
define('PASSWORD_BLOWFISH',  'blowfish');      // Algorithm from crypt()
70
define('PASSWORD_SHA256',    'sha256');        // Algorithm from crypt()
70
define('PASSWORD_SHA256',    'sha256');        // Algorithm from crypt()
71
define('PASSWORD_SHA512',    'sha512');        // Algorithm from crypt()
71
define('PASSWORD_SHA512',    'sha512');        // Algorithm from crypt()
72
define('PASSWORD_VTS_MCF1',  OID_MCF_VTS_V1);  // Algorithm from ViaThinkSoft
72
define('PASSWORD_VTS_MCF1',  OID_MCF_VTS_V1);  // Algorithm from ViaThinkSoft
73
// Other valid values (already defined in PHP):
73
// Other valid values (already defined in PHP):
74
// - PASSWORD_DEFAULT
74
// - PASSWORD_DEFAULT
75
// - PASSWORD_BCRYPT
75
// - PASSWORD_BCRYPT
76
// - PASSWORD_ARGON2I
76
// - PASSWORD_ARGON2I
77
// - PASSWORD_ARGON2ID
77
// - PASSWORD_ARGON2ID
78
 
78
 
79
// --- Part 1: Modular Crypt Format encode/decode
79
// --- Part 1: Modular Crypt Format encode/decode
80
 
80
 
81
function crypt_modular_format_encode($id, $bin_salt, $bin_hash, $params=null) {
81
function crypt_modular_format_encode($id, $bin_salt, $bin_hash, $params=null) {
82
        // $<id>[$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
82
        // $<id>[$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
83
        $out = '$'.$id;
83
        $out = '$'.$id;
84
        if (!is_null($params)) {
84
        if (!is_null($params)) {
85
                $ary_params = array();
85
                $ary_params = array();
86
                foreach ($params as $name => $value) {
86
                foreach ($params as $name => $value) {
87
                        $ary_params[] = "$name=$value";
87
                        $ary_params[] = "$name=$value";
88
                }
88
                }
89
                $out .= '$'.implode(',',$ary_params);
89
                $out .= '$'.implode(',',$ary_params);
90
        }
90
        }
91
        $out .= '$'.crypt_radix64_encode($bin_salt);
91
        $out .= '$'.crypt_radix64_encode($bin_salt);
92
        $out .= '$'.crypt_radix64_encode($bin_hash);
92
        $out .= '$'.crypt_radix64_encode($bin_hash);
93
        return $out;
93
        return $out;
94
}
94
}
95
 
95
 
96
function crypt_modular_format_decode($mcf) {
96
function crypt_modular_format_decode($mcf) {
97
        $ary = explode('$', $mcf);
97
        $ary = explode('$', $mcf);
98
 
98
 
99
        $dummy = array_shift($ary);
99
        $dummy = array_shift($ary);
100
        if ($dummy !== '') return false;
100
        if ($dummy !== '') return false;
101
 
101
 
102
        $dummy = array_shift($ary);
102
        $dummy = array_shift($ary);
103
        $id = $dummy;
103
        $id = $dummy;
104
 
104
 
105
        $params = array();
105
        $params = array();
106
        $dummy = array_shift($ary);
106
        $dummy = array_shift($ary);
107
        if (strpos($dummy, '=') !== false) {
107
        if (strpos($dummy, '=') !== false) {
108
                $params_ary = explode(',',$dummy);
108
                $params_ary = explode(',',$dummy);
109
                foreach ($params_ary as $param) {
109
                foreach ($params_ary as $param) {
110
                        $bry = explode('=', $param, 2);
110
                        $bry = explode('=', $param, 2);
111
                        if (count($bry) > 1) {
111
                        if (count($bry) > 1) {
112
                                $params[$bry[0]] = $bry[1];
112
                                $params[$bry[0]] = $bry[1];
113
                        }
113
                        }
114
                }
114
                }
115
        } else {
115
        } else {
116
                array_unshift($ary, $dummy);
116
                array_unshift($ary, $dummy);
117
        }
117
        }
118
 
118
 
119
        if (count($ary) > 1) {
119
        if (count($ary) > 1) {
120
                $dummy = array_shift($ary);
120
                $dummy = array_shift($ary);
121
                $bin_salt = crypt_radix64_decode($dummy);
121
                $bin_salt = crypt_radix64_decode($dummy);
122
        } else {
122
        } else {
123
                $bin_salt = '';
123
                $bin_salt = '';
124
        }
124
        }
125
 
125
 
126
        $dummy = array_shift($ary);
126
        $dummy = array_shift($ary);
127
        $bin_hash = crypt_radix64_decode($dummy);
127
        $bin_hash = crypt_radix64_decode($dummy);
128
 
128
 
129
        return array('id' => $id, 'salt' => $bin_salt, 'hash' => $bin_hash, 'params' => $params);
129
        return array('id' => $id, 'salt' => $bin_salt, 'hash' => $bin_hash, 'params' => $params);
130
}
130
}
131
 
131
 
132
// --- Part 2: ViaThinkSoft Modular Crypt Format 1.0
132
// --- Part 2: ViaThinkSoft Modular Crypt Format 1.0
133
 
133
 
134
function vts_crypt_version($hash) {
134
function vts_crypt_version($hash) {
135
        if (str_starts_with($hash, '$'.OID_MCF_VTS_V1.'$')) {
135
        if (str_starts_with($hash, '$'.OID_MCF_VTS_V1.'$')) {
136
                return '1';
136
                return '1';
137
        } else {
137
        } else {
138
                return '0';
138
                return '0';
139
        }
139
        }
140
}
140
}
141
 
141
 
142
function vts_crypt_hash($algo, $str_password, $str_salt, $ver='1', $mode='ps', $iterations=0/*default*/) {
142
function vts_crypt_hash($algo, $str_password, $str_salt, $ver='1', $mode='ps', $iterations=0/*default*/) {
143
        if ($ver == '1') {
143
        if ($ver == '1') {
144
                if ($mode == 'sp') {
144
                if ($mode == 'sp') {
145
                        $payload = $str_salt.$str_password;
145
                        $payload = $str_salt.$str_password;
146
                        $algo_supported_natively = in_array($algo, hash_algos());
-
 
147
                        if (!$algo_supported_natively && str_starts_with($algo, 'sha3-') && method_exists('\bb\Sha3\Sha3', 'hash')) {
146
                        if (!hash_supported_natively($algo) && str_starts_with($algo, 'sha3-') && method_exists('\bb\Sha3\Sha3', 'hash')) {
148
                                $bits = explode('-',$algo)[1];
147
                                $bits = explode('-',$algo)[1];
149
                                $bin_hash = \bb\Sha3\Sha3::hash($payload, $bits, true);
148
                                $bin_hash = \bb\Sha3\Sha3::hash($payload, $bits, true);
150
                        } else {
149
                        } else {
151
                                $bin_hash = hash($algo, $payload, true);
150
                                $bin_hash = hash($algo, $payload, true);
152
                        }
151
                        }
153
                } else if ($mode == 'ps') {
152
                } else if ($mode == 'ps') {
154
                        $payload = $str_password.$str_salt;
153
                        $payload = $str_password.$str_salt;
155
                        $algo_supported_natively = in_array($algo, hash_algos());
-
 
156
                        if (!$algo_supported_natively && str_starts_with($algo, 'sha3-') && method_exists('\bb\Sha3\Sha3', 'hash')) {
154
                        if (!hash_supported_natively($algo) && str_starts_with($algo, 'sha3-') && method_exists('\bb\Sha3\Sha3', 'hash')) {
157
                                $bits = explode('-',$algo)[1];
155
                                $bits = explode('-',$algo)[1];
158
                                $bin_hash = \bb\Sha3\Sha3::hash($payload, $bits, true);
156
                                $bin_hash = \bb\Sha3\Sha3::hash($payload, $bits, true);
159
                        } else {
157
                        } else {
160
                                $bin_hash = hash($algo, $payload, true);
158
                                $bin_hash = hash($algo, $payload, true);
161
                        }
159
                        }
162
                } else if ($mode == 'sps') {
160
                } else if ($mode == 'sps') {
163
                        $payload = $str_salt.$str_password.$str_salt;
161
                        $payload = $str_salt.$str_password.$str_salt;
164
                        $algo_supported_natively = in_array($algo, hash_algos());
-
 
165
                        if (!$algo_supported_natively && str_starts_with($algo, 'sha3-') && method_exists('\bb\Sha3\Sha3', 'hash')) {
162
                        if (!hash_supported_natively($algo) && str_starts_with($algo, 'sha3-') && method_exists('\bb\Sha3\Sha3', 'hash')) {
166
                                $bits = explode('-',$algo)[1];
163
                                $bits = explode('-',$algo)[1];
167
                                $bin_hash = \bb\Sha3\Sha3::hash($payload, $bits, true);
164
                                $bin_hash = \bb\Sha3\Sha3::hash($payload, $bits, true);
168
                        } else {
165
                        } else {
169
                                $bin_hash = hash($algo, $payload, true);
166
                                $bin_hash = hash($algo, $payload, true);
170
                        }
167
                        }
171
                } else if ($mode == 'hmac') {
168
                } else if ($mode == 'hmac') {
172
                        if (version_compare(PHP_VERSION, '7.2.0') >= 0) {
-
 
173
                                $algo_supported_natively = in_array($algo, hash_hmac_algos());
-
 
174
                        } else {
-
 
175
                                $algo_supported_natively = in_array($algo, hash_algos());
-
 
176
                        }
-
 
177
                        if (!$algo_supported_natively && str_starts_with($algo, 'sha3-') && method_exists('\bb\Sha3\Sha3', 'hash_hmac')) {
169
                        if (!hash_hmac_supported_natively($algo) && str_starts_with($algo, 'sha3-') && method_exists('\bb\Sha3\Sha3', 'hash_hmac')) {
178
                                $bits = explode('-',$algo)[1];
170
                                $bits = explode('-',$algo)[1];
179
                                $bin_hash = \bb\Sha3\Sha3::hash_hmac($str_password, $str_salt, $bits, true);
171
                                $bin_hash = \bb\Sha3\Sha3::hash_hmac($str_password, $str_salt, $bits, true);
180
                        } else {
172
                        } else {
181
                                $bin_hash = hash_hmac($algo, $str_password, $str_salt, true);
173
                                $bin_hash = hash_hmac($algo, $str_password, $str_salt, true);
182
                        }
174
                        }
183
                } else if ($mode == 'pbkdf2') {
175
                } else if ($mode == 'pbkdf2') {
184
                        $algo_supported_natively = in_array($algo, hash_algos());
-
 
185
                        if (!$algo_supported_natively && str_starts_with($algo, 'sha3-') && method_exists('\bb\Sha3\Sha3', 'hash_pbkdf2')) {
176
                        if (!hash_pbkdf2_supported_natively($algo) && str_starts_with($algo, 'sha3-') && method_exists('\bb\Sha3\Sha3', 'hash_pbkdf2')) {
186
                                if ($iterations == 0) {
177
                                if ($iterations == 0) {
187
                                        $iterations = 2000; // because userland implementations are much slower, we must choose a small value...
178
                                        $iterations = 2000; // because userland implementations are much slower, we must choose a small value...
188
                                }
179
                                }
189
                                $bits = explode('-',$algo)[1];
180
                                $bits = explode('-',$algo)[1];
190
                                $bin_hash = \bb\Sha3\Sha3::hash_pbkdf2($str_password, $str_salt, $iterations, $bits, 0, true);
181
                                $bin_hash = \bb\Sha3\Sha3::hash_pbkdf2($str_password, $str_salt, $iterations, $bits, 0, true);
191
                        } else {
182
                        } else {
192
                                if ($iterations == 0) {
183
                                if ($iterations == 0) {
193
                                        // Recommendations taken from https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2
184
                                        // Recommendations taken from https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2
194
                                        // I am not sure if these recommendations are correct. They write PBKDF2-HMAC-SHA1...
185
                                        // I am not sure if these recommendations are correct. They write PBKDF2-HMAC-SHA1...
195
                                        // Does this count for us, or does hash_pbkdf2() implement PBKDF2-SHA1 rather than PBKDF2-HMAC-SHA1?
186
                                        // Does this count for us, or does hash_pbkdf2() implement PBKDF2-SHA1 rather than PBKDF2-HMAC-SHA1?
196
                                        if      ($algo == 'sha3-512')    $iterations =  100000;
187
                                        if      ($algo == 'sha3-512')    $iterations =  100000;
197
                                        else if ($algo == 'sha3-384')    $iterations =  100000;
188
                                        else if ($algo == 'sha3-384')    $iterations =  100000;
198
                                        else if ($algo == 'sha3-256')    $iterations =  100000;
189
                                        else if ($algo == 'sha3-256')    $iterations =  100000;
199
                                        else if ($algo == 'sha3-224')    $iterations =  100000;
190
                                        else if ($algo == 'sha3-224')    $iterations =  100000;
200
                                        else if ($algo == 'sha512')      $iterations =  210000; // value by owasp.org cheatcheat (28.02.2023)
191
                                        else if ($algo == 'sha512')      $iterations =  210000; // value by owasp.org cheatcheat (28.02.2023)
201
                                        else if ($algo == 'sha512/256')  $iterations =  210000; // value by owasp.org cheatcheat (28.02.2023)
192
                                        else if ($algo == 'sha512/256')  $iterations =  210000; // value by owasp.org cheatcheat (28.02.2023)
202
                                        else if ($algo == 'sha512/224')  $iterations =  210000; // value by owasp.org cheatcheat (28.02.2023)
193
                                        else if ($algo == 'sha512/224')  $iterations =  210000; // value by owasp.org cheatcheat (28.02.2023)
203
                                        else if ($algo == 'sha384')      $iterations =  600000;
194
                                        else if ($algo == 'sha384')      $iterations =  600000;
204
                                        else if ($algo == 'sha256')      $iterations =  600000; // value by owasp.org cheatcheat (28.02.2023)
195
                                        else if ($algo == 'sha256')      $iterations =  600000; // value by owasp.org cheatcheat (28.02.2023)
205
                                        else if ($algo == 'sha224')      $iterations =  600000;
196
                                        else if ($algo == 'sha224')      $iterations =  600000;
206
                                        else if ($algo == 'sha1')        $iterations = 1300000; // value by owasp.org cheatcheat (28.02.2023)
197
                                        else if ($algo == 'sha1')        $iterations = 1300000; // value by owasp.org cheatcheat (28.02.2023)
207
                                        else if ($algo == 'md5')         $iterations = 5000000;
198
                                        else if ($algo == 'md5')         $iterations = 5000000;
208
                                        else                             $iterations =    5000;
199
                                        else                             $iterations =    5000;
209
                                }
200
                                }
210
                                $bin_hash = hash_pbkdf2($algo, $str_password, $str_salt, $iterations, 0, true);
201
                                $bin_hash = hash_pbkdf2($algo, $str_password, $str_salt, $iterations, 0, true);
211
                        }
202
                        }
212
                } else {
203
                } else {
213
                        throw new Exception("Invalid VTS crypt version 1 mode. Expect sp, ps, sps, hmac, or pbkdf2.");
204
                        throw new Exception("Invalid VTS crypt version 1 mode. Expect sp, ps, sps, hmac, or pbkdf2.");
214
                }
205
                }
215
                $bin_salt = $str_salt;
206
                $bin_salt = $str_salt;
216
                $params = array();
207
                $params = array();
217
                $params['a'] = $algo;
208
                $params['a'] = $algo;
218
                $params['m'] = $mode;
209
                $params['m'] = $mode;
219
                if ($mode == 'pbkdf2') $params['i'] = $iterations;
210
                if ($mode == 'pbkdf2') $params['i'] = $iterations;
220
                return crypt_modular_format_encode(OID_MCF_VTS_V1, $bin_salt, $bin_hash, $params);
211
                return crypt_modular_format_encode(OID_MCF_VTS_V1, $bin_salt, $bin_hash, $params);
221
        } else {
212
        } else {
222
                throw new Exception("Invalid VTS crypt version, expect 1.");
213
                throw new Exception("Invalid VTS crypt version, expect 1.");
223
        }
214
        }
224
}
215
}
225
 
216
 
226
function vts_crypt_verify($password, $hash): bool {
217
function vts_crypt_verify($password, $hash): bool {
227
        $ver = vts_crypt_version($hash);
218
        $ver = vts_crypt_version($hash);
228
        if ($ver == '1') {
219
        if ($ver == '1') {
229
                // Decode the MCF hash parameters
220
                // Decode the MCF hash parameters
230
                $data = crypt_modular_format_decode($hash);
221
                $data = crypt_modular_format_decode($hash);
231
                if ($data === false) throw new Exception('Invalid auth key');
222
                if ($data === false) throw new Exception('Invalid auth key');
232
                $id = $data['id'];
223
                $id = $data['id'];
233
                $bin_salt = $data['salt'];
224
                $bin_salt = $data['salt'];
234
                $bin_hash = $data['hash'];
225
                $bin_hash = $data['hash'];
235
                $params = $data['params'];
226
                $params = $data['params'];
236
 
227
 
237
                if (!isset($params['a'])) throw new Exception('Param "a" (algo) missing');
228
                if (!isset($params['a'])) throw new Exception('Param "a" (algo) missing');
238
                $algo = $params['a'];
229
                $algo = $params['a'];
239
 
230
 
240
                if (!isset($params['m'])) throw new Exception('Param "m" (mode) missing');
231
                if (!isset($params['m'])) throw new Exception('Param "m" (mode) missing');
241
                $mode = $params['m'];
232
                $mode = $params['m'];
242
 
233
 
243
                if ($mode == 'pbkdf2') {
234
                if ($mode == 'pbkdf2') {
244
                        if (!isset($params['i'])) throw new Exception('Param "i" (iterations) missing');
235
                        if (!isset($params['i'])) throw new Exception('Param "i" (iterations) missing');
245
                        $iterations = $params['i'];
236
                        $iterations = $params['i'];
246
                } else {
237
                } else {
247
                        $iterations = 0;
238
                        $iterations = 0;
248
                }
239
                }
249
 
240
 
250
                // Create a VTS MCF 1.0 hash based on the parameters of $hash and the password $password
241
                // Create a VTS MCF 1.0 hash based on the parameters of $hash and the password $password
251
                $calc_authkey_1 = vts_crypt_hash($algo, $password, $bin_salt, $ver, $mode, $iterations);
242
                $calc_authkey_1 = vts_crypt_hash($algo, $password, $bin_salt, $ver, $mode, $iterations);
252
 
243
 
253
                // We rewrite the MCF to make sure that they match (if params have the wrong order)
244
                // We rewrite the MCF to make sure that they match (if params have the wrong order)
254
                $calc_authkey_2 = crypt_modular_format_encode($id, $bin_salt, $bin_hash, $params);
245
                $calc_authkey_2 = crypt_modular_format_encode($id, $bin_salt, $bin_hash, $params);
255
 
246
 
256
                return hash_equals($calc_authkey_1, $calc_authkey_2);
247
                return hash_equals($calc_authkey_1, $calc_authkey_2);
257
        } else {
248
        } else {
258
                throw new Exception("Invalid VTS crypt version, expect 1.");
249
                throw new Exception("Invalid VTS crypt version, expect 1.");
259
        }
250
        }
260
}
251
}
261
 
252
 
262
// --- Part 3: vts_password_hash() and vts_password_verify()
253
// --- Part 3: vts_password_hash() and vts_password_verify()
263
 
254
 
264
/** This function extends password_verify() by adding ViaThinkSoft Modular Crypt Format 1.0.
255
/** This function extends password_verify() by adding ViaThinkSoft Modular Crypt Format 1.0.
265
 * @param string $password to be checked
256
 * @param string $password to be checked
266
 * @param string $hash Hash created by crypt(), password_hash(), or vts_password_hash().
257
 * @param string $hash Hash created by crypt(), password_hash(), or vts_password_hash().
267
 * @return bool true if password is valid
258
 * @return bool true if password is valid
268
 */
259
 */
269
function vts_password_verify($password, $hash): bool {
260
function vts_password_verify($password, $hash): bool {
270
        if (vts_crypt_version($hash) != '0') {
261
        if (vts_crypt_version($hash) != '0') {
271
                // Hash created by vts_password_hash(), or vts_crypt_hash()
262
                // Hash created by vts_password_hash(), or vts_crypt_hash()
272
                return vts_crypt_verify($password, $hash);
263
                return vts_crypt_verify($password, $hash);
273
        } else {
264
        } else {
274
                // Hash created by vts_password_hash(), password_hash(), or crypt()
265
                // Hash created by vts_password_hash(), password_hash(), or crypt()
275
                return password_verify($password, $hash);
266
                return password_verify($password, $hash);
276
        }
267
        }
277
}
268
}
278
 
269
 
279
/** This function extends password_hash() with the algorithms supported by crypt().
270
/** This function extends password_hash() with the algorithms supported by crypt().
280
 * It also adds vts_crypt_hash() which implements the ViaThinkSoft Modular Crypt Format 1.0.
271
 * It also adds vts_crypt_hash() which implements the ViaThinkSoft Modular Crypt Format 1.0.
281
 * The result can be verified using vts_password_verify().
272
 * The result can be verified using vts_password_verify().
282
 * @param string $password to be hashed
273
 * @param string $password to be hashed
283
 * @param mixed $algo algorithm
274
 * @param mixed $algo algorithm
284
 * @param array $options options for the hashing algorithm
275
 * @param array $options options for the hashing algorithm
285
 * @return string Crypt style password hash
276
 * @return string Crypt style password hash
286
 */
277
 */
287
function vts_password_hash($password, $algo, $options=array()): string {
278
function vts_password_hash($password, $algo, $options=array()): string {
288
        $crypt_salt = null;
279
        $crypt_salt = null;
289
        if (($algo === PASSWORD_STD_DES) && defined('CRYPT_STD_DES')) {
280
        if (($algo === PASSWORD_STD_DES) && defined('CRYPT_STD_DES')) {
290
                // Standard DES-based hash with a two character salt from the alphabet "./0-9A-Za-z". Using invalid characters in the salt will cause crypt() to fail.
281
                // Standard DES-based hash with a two character salt from the alphabet "./0-9A-Za-z". Using invalid characters in the salt will cause crypt() to fail.
291
                $crypt_salt = des_compat_salt(2);
282
                $crypt_salt = des_compat_salt(2);
292
        } else if (($algo === PASSWORD_EXT_DES) && defined('CRYPT_EXT_DES')) {
283
        } else if (($algo === PASSWORD_EXT_DES) && defined('CRYPT_EXT_DES')) {
293
                // Extended DES-based hash. The "salt" is a 9-character string consisting of an underscore followed by 4 characters of iteration count and 4 characters of salt. Each of these 4-character strings encode 24 bits, least significant character first. The values 0 to 63 are encoded as ./0-9A-Za-z. Using invalid characters in the salt will cause crypt() to fail.
284
                // Extended DES-based hash. The "salt" is a 9-character string consisting of an underscore followed by 4 characters of iteration count and 4 characters of salt. Each of these 4-character strings encode 24 bits, least significant character first. The values 0 to 63 are encoded as ./0-9A-Za-z. Using invalid characters in the salt will cause crypt() to fail.
294
                $iterations = isset($options['iterations']) ? $options['iterations'] : 725;
285
                $iterations = isset($options['iterations']) ? $options['iterations'] : 725;
295
                $crypt_salt = '_' . base64_int_encode($iterations) . des_compat_salt(4);
286
                $crypt_salt = '_' . base64_int_encode($iterations) . des_compat_salt(4);
296
        } else if (($algo === PASSWORD_MD5) && defined('CRYPT_MD5')) {
287
        } else if (($algo === PASSWORD_MD5) && defined('CRYPT_MD5')) {
297
                // MD5 hashing with a twelve character salt starting with $1$
288
                // MD5 hashing with a twelve character salt starting with $1$
298
                $crypt_salt = '$1$'.des_compat_salt(12).'$';
289
                $crypt_salt = '$1$'.des_compat_salt(12).'$';
299
        } else if (($algo === PASSWORD_BLOWFISH) && defined('CRYPT_BLOWFISH')) {
290
        } else if (($algo === PASSWORD_BLOWFISH) && defined('CRYPT_BLOWFISH')) {
300
                // Blowfish hashing with a salt as follows: "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt will cause crypt() to return a zero-length string. The two digit cost parameter is the base-2 logarithm of the iteration count for the underlying Blowfish-based hashing algorithm and must be in range 04-31, values outside this range will cause crypt() to fail. "$2x$" hashes are potentially weak; "$2a$" hashes are compatible and mitigate this weakness. For new hashes, "$2y$" should be used.
291
                // Blowfish hashing with a salt as follows: "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt will cause crypt() to return a zero-length string. The two digit cost parameter is the base-2 logarithm of the iteration count for the underlying Blowfish-based hashing algorithm and must be in range 04-31, values outside this range will cause crypt() to fail. "$2x$" hashes are potentially weak; "$2a$" hashes are compatible and mitigate this weakness. For new hashes, "$2y$" should be used.
301
                $algo = '$2y$'; // most secure
292
                $algo = '$2y$'; // most secure
302
                $cost = isset($options['cost']) ? $options['cost'] : 10;
293
                $cost = isset($options['cost']) ? $options['cost'] : 10;
303
                $crypt_salt = $algo.str_pad($cost,2,'0',STR_PAD_LEFT).'$'.des_compat_salt(22).'$';
294
                $crypt_salt = $algo.str_pad($cost,2,'0',STR_PAD_LEFT).'$'.des_compat_salt(22).'$';
304
        } else if (($algo === PASSWORD_SHA256) && defined('CRYPT_SHA256')) {
295
        } else if (($algo === PASSWORD_SHA256) && defined('CRYPT_SHA256')) {
305
                // SHA-256 hash with a sixteen character salt prefixed with $5$. If the salt string starts with 'rounds=<N>$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.
296
                // SHA-256 hash with a sixteen character salt prefixed with $5$. If the salt string starts with 'rounds=<N>$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.
306
                $algo = '$5$';
297
                $algo = '$5$';
307
                $rounds = isset($options['rounds']) ? $options['rounds'] : 5000;
298
                $rounds = isset($options['rounds']) ? $options['rounds'] : 5000;
308
                $crypt_salt = $algo.'rounds='.$rounds.'$'.des_compat_salt(16).'$';
299
                $crypt_salt = $algo.'rounds='.$rounds.'$'.des_compat_salt(16).'$';
309
        } else if (($algo === PASSWORD_SHA512) && defined('CRYPT_SHA512')) {
300
        } else if (($algo === PASSWORD_SHA512) && defined('CRYPT_SHA512')) {
310
                // SHA-512 hash with a sixteen character salt prefixed with $6$. If the salt string starts with 'rounds=<N>$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.
301
                // SHA-512 hash with a sixteen character salt prefixed with $6$. If the salt string starts with 'rounds=<N>$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.
311
                $algo = '$6$';
302
                $algo = '$6$';
312
                $rounds = isset($options['rounds']) ? $options['rounds'] : 5000;
303
                $rounds = isset($options['rounds']) ? $options['rounds'] : 5000;
313
                $crypt_salt = $algo.'rounds='.$rounds.'$'.des_compat_salt(16).'$';
304
                $crypt_salt = $algo.'rounds='.$rounds.'$'.des_compat_salt(16).'$';
314
        }
305
        }
315
 
306
 
316
        if (!is_null($crypt_salt)) {
307
        if (!is_null($crypt_salt)) {
317
                // Algorithms: PASSWORD_STD_DES
308
                // Algorithms: PASSWORD_STD_DES
318
                //             PASSWORD_EXT_DES
309
                //             PASSWORD_EXT_DES
319
                //             PASSWORD_MD5
310
                //             PASSWORD_MD5
320
                //             PASSWORD_BLOWFISH
311
                //             PASSWORD_BLOWFISH
321
                //             PASSWORD_SHA256
312
                //             PASSWORD_SHA256
322
                //             PASSWORD_SHA512
313
                //             PASSWORD_SHA512
323
                $out = crypt($password, $crypt_salt);
314
                $out = crypt($password, $crypt_salt);
324
                if (strlen($out) < 13) throw new Exception("crypt() failed");
315
                if (strlen($out) < 13) throw new Exception("crypt() failed");
325
                return $out;
316
                return $out;
326
        } else if ($algo === PASSWORD_VTS_MCF1) {
317
        } else if ($algo === PASSWORD_VTS_MCF1) {
327
                // Algorithms: PASSWORD_VTS_MCF1
318
                // Algorithms: PASSWORD_VTS_MCF1
328
                $ver  = '1';
319
                $ver  = '1';
329
                $algo = isset($options['algo']) ? $options['algo'] : 'sha3-512';
320
                $algo = isset($options['algo']) ? $options['algo'] : 'sha3-512';
330
                $mode = isset($options['mode']) ? $options['mode'] : 'ps';
321
                $mode = isset($options['mode']) ? $options['mode'] : 'ps';
331
                $iterations = isset($options['iterations']) ? $options['iterations'] : 0/*default*/;
322
                $iterations = isset($options['iterations']) ? $options['iterations'] : 0/*default*/;
332
                $salt_len = isset($options['salt_length']) ? $options['salt_length'] : 50;
323
                $salt_len = isset($options['salt_length']) ? $options['salt_length'] : 50;
333
                $salt = random_bytes_ex($salt_len, true, true);
324
                $salt = random_bytes_ex($salt_len, true, true);
334
                return vts_crypt_hash($algo, $password, $salt, $ver, $mode, $iterations);
325
                return vts_crypt_hash($algo, $password, $salt, $ver, $mode, $iterations);
335
        } else {
326
        } else {
336
                // Algorithms: PASSWORD_DEFAULT
327
                // Algorithms: PASSWORD_DEFAULT
337
                //             PASSWORD_BCRYPT
328
                //             PASSWORD_BCRYPT
338
                //             PASSWORD_ARGON2I
329
                //             PASSWORD_ARGON2I
339
                //             PASSWORD_ARGON2ID
330
                //             PASSWORD_ARGON2ID
340
                return password_hash($password, $algo, $options);
331
                return password_hash($password, $algo, $options);
341
        }
332
        }
342
}
333
}
343
 
334
 
344
// --- Part 4: Useful functions required by the crypt-functions
335
// --- Part 4: Useful functions required by the crypt-functions
345
 
336
 
346
define('BASE64_RFC4648_ALPHABET', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/');
337
define('BASE64_RFC4648_ALPHABET', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/');
347
define('BASE64_CRYPT_ALPHABET',   './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
338
define('BASE64_CRYPT_ALPHABET',   './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
348
 
339
 
349
function des_compat_salt($salt_len) {
340
function des_compat_salt($salt_len) {
350
        if ($salt_len <= 0) return '';
341
        if ($salt_len <= 0) return '';
351
        $characters = BASE64_CRYPT_ALPHABET;
342
        $characters = BASE64_CRYPT_ALPHABET;
352
        $salt = '';
343
        $salt = '';
353
        $bytes = random_bytes_ex($salt_len, true, true);
344
        $bytes = random_bytes_ex($salt_len, true, true);
354
        for ($i=0; $i<$salt_len; $i++) {
345
        for ($i=0; $i<$salt_len; $i++) {
355
                $salt .= $characters[ord($bytes[$i]) % strlen($characters)];
346
                $salt .= $characters[ord($bytes[$i]) % strlen($characters)];
356
        }
347
        }
357
        return $salt;
348
        return $salt;
358
}
349
}
359
 
350
 
360
function base64_int_encode($num) {
351
function base64_int_encode($num) {
361
        // https://stackoverflow.com/questions/15534982/which-iteration-rules-apply-on-crypt-using-crypt-ext-des
352
        // https://stackoverflow.com/questions/15534982/which-iteration-rules-apply-on-crypt-using-crypt-ext-des
362
        $alphabet_raw = BASE64_CRYPT_ALPHABET;
353
        $alphabet_raw = BASE64_CRYPT_ALPHABET;
363
        $alphabet = str_split($alphabet_raw);
354
        $alphabet = str_split($alphabet_raw);
364
        $arr = array();
355
        $arr = array();
365
        $base = sizeof($alphabet);
356
        $base = sizeof($alphabet);
366
        while ($num) {
357
        while ($num) {
367
                $rem = $num % $base;
358
                $rem = $num % $base;
368
                $num = (int)($num / $base);
359
                $num = (int)($num / $base);
369
                $arr[] = $alphabet[$rem];
360
                $arr[] = $alphabet[$rem];
370
        }
361
        }
371
        $string = implode($arr);
362
        $string = implode($arr);
372
        return str_pad($string, 4, '.', STR_PAD_RIGHT);
363
        return str_pad($string, 4, '.', STR_PAD_RIGHT);
373
}
364
}
374
 
365
 
375
function crypt_radix64_encode($str) {
366
function crypt_radix64_encode($str) {
376
        $x = $str;
367
        $x = $str;
377
        $x = base64_encode($x);
368
        $x = base64_encode($x);
378
        $x = rtrim($x, '='); // remove padding
369
        $x = rtrim($x, '='); // remove padding
379
        $x = strtr($x, BASE64_RFC4648_ALPHABET, BASE64_CRYPT_ALPHABET);
370
        $x = strtr($x, BASE64_RFC4648_ALPHABET, BASE64_CRYPT_ALPHABET);
380
        return $x;
371
        return $x;
381
}
372
}
382
 
373
 
383
function crypt_radix64_decode($str) {
374
function crypt_radix64_decode($str) {
384
        $x = $str;
375
        $x = $str;
385
        $x = strtr($x, BASE64_CRYPT_ALPHABET, BASE64_RFC4648_ALPHABET);
376
        $x = strtr($x, BASE64_CRYPT_ALPHABET, BASE64_RFC4648_ALPHABET);
386
        $x = base64_decode($x);
377
        $x = base64_decode($x);
387
        return $x;
378
        return $x;
388
}
379
}
-
 
380
 
-
 
381
function hash_supported_natively($algo) {
-
 
382
        if (version_compare(PHP_VERSION, '5.1.2') >= 0) {
-
 
383
                return in_array($algo, hash_algos());
-
 
384
        } else {
-
 
385
                return false;
-
 
386
        }
-
 
387
}
-
 
388
 
-
 
389
function hash_hmac_supported_natively($algo): bool {
-
 
390
        if (version_compare(PHP_VERSION, '7.2.0') >= 0) {
-
 
391
                return in_array($algo, hash_hmac_algos());
-
 
392
        } else if (version_compare(PHP_VERSION, '5.1.2') >= 0) {
-
 
393
                return in_array($algo, hash_algos());
-
 
394
        } else {
-
 
395
                return false;
-
 
396
        }
-
 
397
}
-
 
398
 
-
 
399
function hash_pbkdf2_supported_natively($algo) {
-
 
400
        return hash_supported_natively($algo);
-
 
401
}
389
 
402
 
390
// --- Part 5: Selftest
403
// --- Part 5: Selftest
391
 
404
 
392
/*
405
/*
393
$rnd = random_bytes_ex(50, true, true);
406
$rnd = random_bytes_ex(50, true, true);
394
assert(crypt_radix64_decode(crypt_radix64_encode($rnd)) === $rnd);
407
assert(crypt_radix64_decode(crypt_radix64_encode($rnd)) === $rnd);
395
 
408
 
396
$password = random_bytes_ex(20, false, true);
409
$password = random_bytes_ex(20, false, true);
397
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_STD_DES)));
410
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_STD_DES)));
398
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_EXT_DES)));
411
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_EXT_DES)));
399
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_MD5)));
412
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_MD5)));
400
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_BLOWFISH)));
413
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_BLOWFISH)));
401
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_SHA256)));
414
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_SHA256)));
402
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_SHA512)));
415
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_SHA512)));
403
assert(vts_password_verify($password,$debug = vts_password_hash($password, PASSWORD_VTS_MCF1, array(
416
assert(vts_password_verify($password,$debug = vts_password_hash($password, PASSWORD_VTS_MCF1, array(
404
        'algo' => 'sha3-512',
417
        'algo' => 'sha3-512',
405
        'mode' => 'pbkdf2',
418
        'mode' => 'pbkdf2',
406
        'iterations' => 5000
419
        'iterations' => 5000
407
))));
420
))));
408
echo "$debug\n";
421
echo "$debug\n";
409
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_DEFAULT)));
422
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_DEFAULT)));
410
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_BCRYPT)));
423
assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_BCRYPT)));
411
if (defined('PASSWORD_ARGON2I'))
424
if (defined('PASSWORD_ARGON2I'))
412
        assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_ARGON2I)));
425
        assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_ARGON2I)));
413
if (defined('PASSWORD_ARGON2ID'))
426
if (defined('PASSWORD_ARGON2ID'))
414
        assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_ARGON2ID)));
427
        assert(vts_password_verify($password,vts_password_hash($password, PASSWORD_ARGON2ID)));
415
echo "OK, Password $password\n";
428
echo "OK, Password $password\n";
416
*/
429
*/
417
 
430