Subversion Repositories php_utils

Rev

Rev 61 | Blame | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * password_hash_ex() function which integrates crypt() algorithms in password_hash().
  5.  * Revision 2023-02-26
  6.  * Copyright 2023 Daniel Marschall, ViaThinkSoft
  7.  *
  8.  * Licensed under the Apache License, Version 2.0 (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
  11.  *
  12.  *     http://www.apache.org/licenses/LICENSE-2.0
  13.  *
  14.  * Unless required by applicable law or agreed to in writing, software
  15.  * distributed under the License is distributed on an "AS IS" BASIS,
  16.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17.  * See the License for the specific language governing permissions and
  18.  * limitations under the License.
  19.  */
  20.  
  21. define('PASSWORD_STD_DES',  'std_des');
  22. define('PASSWORD_EXT_DES',  'ext_des');
  23. define('PASSWORD_MD5',      'md5');
  24. define('PASSWORD_BLOWFISH', 'blowfish');
  25. define('PASSWORD_SHA256',   'sha256');
  26. define('PASSWORD_SHA512',   'sha512');
  27.  
  28. function des_compat_salt($salt_len) {
  29.         $characters = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  30.         $salt = '';
  31.         for ($i=0; $i<$salt_len; $i++) {
  32.                 $salt .= $characters[rand(0, strlen($characters)-1)]; // TODO: use rand() to make the RND cryptographical secure
  33.         }
  34.         return $salt;
  35. }
  36.  
  37. function base64_int_encode($num) {
  38.         // https://stackoverflow.com/questions/15534982/which-iteration-rules-apply-on-crypt-using-crypt-ext-des
  39.         $alphabet_raw='./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  40.         $alphabet=str_split($alphabet_raw);
  41.         $arr=array();
  42.         $base=sizeof($alphabet);
  43.         while($num) {
  44.                 $rem=$num % $base;
  45.                 $num=(int)($num / $base);
  46.                 $arr[]=$alphabet[$rem];
  47.         }
  48.         $string=implode($arr);
  49.         return str_pad($string, 4, '.', STR_PAD_RIGHT);
  50. }
  51.  
  52. /** This function extends password_hash() with the algorithms supported by crypt().
  53.  * The result can be verified using password_verify().
  54.  * @param string $password to be hashed
  55.  * @param mixed $algo algorithm
  56.  * @param array $options options for the hashing algorithm
  57.  * @return string Crypt compatible password hash
  58.  */
  59. function password_hash_ex($password, $algo, $options=array()) {
  60.         if (($algo === PASSWORD_STD_DES) && defined('CRYPT_STD_DES')) {
  61.                 // 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.
  62.                 $salt = des_compat_salt(2);
  63.                 return crypt($password, $salt);
  64.         } else if (($algo === PASSWORD_EXT_DES) && defined('CRYPT_EXT_DES')) {
  65.                 // 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.
  66.                 $iterations = isset($options['iterations']) ? $options['iterations'] : 725;
  67.                 $salt = '_' . base64_int_encode($iterations) . des_compat_salt(4);
  68.                 return crypt($password, $salt);
  69.         } else if (($algo === PASSWORD_MD5) && defined('CRYPT_MD5')) {
  70.                 // MD5 hashing with a twelve character salt starting with $1$
  71.                 $salt = '$1$'.des_compat_salt(12).'$';
  72.                 return crypt($password, $salt);
  73.         } else if (($algo === PASSWORD_BLOWFISH) && defined('CRYPT_BLOWFISH')) {
  74.                 // 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.
  75.                 $algo = '$2y$'; // most secure
  76.                 $cost = isset($options['cost']) ? $options['cost'] : 10;
  77.                 $salt = $algo.str_pad($cost,2,'0',STR_PAD_LEFT).'$'.des_compat_salt(22).'$';
  78.                 return crypt($password, $salt);
  79.         } else if (($algo === PASSWORD_SHA256) && defined('CRYPT_SHA256')) {
  80.                 // 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.
  81.                 $algo = '$5$';
  82.                 $rounds = isset($options['rounds']) ? $options['rounds'] : 5000;
  83.                 $salt = $algo.'rounds='.$rounds.'$'.des_compat_salt(16).'$';
  84.                 return crypt($password, $salt);
  85.         } else if (($algo === PASSWORD_SHA512) && defined('CRYPT_SHA512')) {
  86.                 // 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.
  87.                 $algo = '$6$';
  88.                 $rounds = isset($options['rounds']) ? $options['rounds'] : 5000;
  89.                 $salt = $algo.'rounds='.$rounds.'$'.des_compat_salt(16).'$';
  90.                 return crypt($password, $salt);
  91.         } else {
  92.                 // $algo === PASSWORD_DEFAULT
  93.                 // $algo === PASSWORD_BCRYPT
  94.                 // $algo === PASSWORD_ARGON2I
  95.                 // $algo === PASSWORD_ARGON2ID
  96.                 return password_hash($password, $algo, $options);
  97.         }
  98. }
  99.  
  100. /*
  101. assert(password_verify('test123',password_hash_ex('test123', PASSWORD_STD_DES)));
  102. assert(password_verify('test123',password_hash_ex('test123', PASSWORD_EXT_DES)));
  103. assert(password_verify('test123',password_hash_ex('test123', PASSWORD_MD5)));
  104. assert(password_verify('test123',password_hash_ex('test123', PASSWORD_BLOWFISH)));
  105. assert(password_verify('test123',password_hash_ex('test123', PASSWORD_SHA256)));
  106. assert(password_verify('test123',password_hash_ex('test123', PASSWORD_SHA512)));
  107. assert(password_verify('test123',password_hash_ex('test123', PASSWORD_DEFAULT)));
  108. assert(password_verify('test123',password_hash_ex('test123', PASSWORD_BCRYPT)));
  109. assert(password_verify('test123',password_hash_ex('test123', PASSWORD_ARGON2I)));
  110. assert(password_verify('test123',password_hash_ex('test123', PASSWORD_ARGON2ID)));
  111. */
  112.