PageRenderTime 162ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/utils/CPasswordHelper.php

https://bitbucket.org/gencer/yii
PHP | 193 lines | 61 code | 16 blank | 116 comment | 21 complexity | fa7c5e769364ab966693d4b5faa3dbd5 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * CPasswordHelper class file.
  4. *
  5. * @author Tom Worster <fsb@thefsb.org>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CPasswordHelper provides a simple API for secure password hashing and verification.
  12. *
  13. * CPasswordHelper uses the Blowfish hash algorithm available in many PHP runtime
  14. * environments through the PHP {@link http://php.net/manual/en/function.crypt.php crypt()}
  15. * built-in function. As of Dec 2012 it is the strongest algorithm available in PHP
  16. * and the only algorithm without some security concerns surrounding it. For this reason,
  17. * CPasswordHelper fails to initialize when run in and environment that does not have
  18. * crypt() and its Blowfish option. Systems with the option include:
  19. * (1) Most *nix systems since PHP 4 (the algorithm is part of the library function crypt(3));
  20. * (2) All PHP systems since 5.3.0; (3) All PHP systems with the
  21. * {@link http://www.hardened-php.net/suhosin/ Suhosin patch}.
  22. * For more information about password hashing, crypt() and Blowfish, please read
  23. * the Yii Wiki article
  24. * {@link http://www.yiiframework.com/wiki/425/use-crypt-for-password-storage/ Use crypt() for password storage}.
  25. * and the
  26. * PHP RFC {@link http://wiki.php.net/rfc/password_hash Adding simple password hashing API}.
  27. *
  28. * CPasswordHelper throws an exception if the Blowfish hash algorithm is not
  29. * available in the runtime PHP's crypt() function. It can be used as follows
  30. *
  31. * Generate a hash from a password:
  32. * <pre>
  33. * $hash = CPasswordHelper::hashPassword($password);
  34. * </pre>
  35. * This hash can be stored in a database (e.g. CHAR(64) CHARACTER SET latin1). The
  36. * hash is usually generated and saved to the database when the user enters a new password.
  37. * But it can also be useful to generate and save a hash after validating a user's
  38. * password in order to change the cost or refresh the salt.
  39. *
  40. * To verify a password, fetch the user's saved hash from the database (into $hash) and:
  41. * <pre>
  42. * if (CPasswordHelper::verifyPassword($password, $hash))
  43. * // password is good
  44. * else
  45. * // password is bad
  46. * </pre>
  47. *
  48. * @author Tom Worster <fsb@thefsb.org>
  49. * @package system.utils
  50. * @since 1.1.14
  51. */
  52. class CPasswordHelper
  53. {
  54. /**
  55. * Check for availability of PHP crypt() with the Blowfish hash option.
  56. * @throws CException if the runtime system does not have PHP crypt() or its Blowfish hash option.
  57. */
  58. protected static function checkBlowfish()
  59. {
  60. if(!function_exists('crypt'))
  61. throw new CException(Yii::t('yii','{class} requires the PHP crypt() function. This system does not have it.',
  62. array('{class}'=>__CLASS__)));
  63. if(!defined('CRYPT_BLOWFISH') || !CRYPT_BLOWFISH)
  64. throw new CException(Yii::t('yii',
  65. '{class} requires the Blowfish option of the PHP crypt() function. This system does not have it.',
  66. array('{class}'=>__CLASS__)));
  67. }
  68. /**
  69. * Generate a secure hash from a password and a random salt.
  70. *
  71. * Uses the
  72. * PHP {@link http://php.net/manual/en/function.crypt.php crypt()} built-in function
  73. * with the Blowfish hash option.
  74. *
  75. * @param string $password The password to be hashed.
  76. * @param int $cost Cost parameter used by the Blowfish hash algorithm.
  77. * The higher the value of cost,
  78. * the longer it takes to generate the hash and to verify a password against it. Higher cost
  79. * therefore slows down a brute-force attack. For best protection against brute for attacks,
  80. * set it to the highest value that is tolerable on production servers. The time taken to
  81. * compute the hash doubles for every increment by one of $cost. So, for example, if the
  82. * hash takes 1 second to compute when $cost is 14 then then the compute time varies as
  83. * 2^($cost - 14) seconds.
  84. * @return string The password hash string, ASCII and not longer than 64 characters.
  85. * @throws CException on bad password parameter or if crypt() with Blowfish hash is not available.
  86. */
  87. public static function hashPassword($password,$cost=13)
  88. {
  89. self::checkBlowfish();
  90. $salt=self::generateSalt($cost);
  91. $hash=crypt($password,$salt);
  92. if(!is_string($hash) || (function_exists('mb_strlen') ? mb_strlen($hash, '8bit') : strlen($hash))<32)
  93. throw new CException(Yii::t('yii','Internal error while generating hash.'));
  94. return $hash;
  95. }
  96. /**
  97. * Verify a password against a hash.
  98. *
  99. * @param string $password The password to verify. If password is empty or not a string, method will return false.
  100. * @param string $hash The hash to verify the password against.
  101. * @return bool True if the password matches the hash.
  102. * @throws CException on bad password or hash parameters or if crypt() with Blowfish hash is not available.
  103. */
  104. public static function verifyPassword($password, $hash)
  105. {
  106. self::checkBlowfish();
  107. if(!is_string($password) || $password==='')
  108. return false;
  109. if (!$password || !preg_match('{^\$2[axy]\$(\d\d)\$[\./0-9A-Za-z]{22}}',$hash,$matches) ||
  110. $matches[1]<4 || $matches[1]>31)
  111. return false;
  112. $test=crypt($password,$hash);
  113. if(!is_string($test) || strlen($test)<32)
  114. return false;
  115. return self::same($test, $hash);
  116. }
  117. /**
  118. * Check for sameness of two strings using an algorithm with timing
  119. * independent of the string values if the subject strings are of equal length.
  120. *
  121. * The function can be useful to prevent timing attacks. For example, if $a and $b
  122. * are both hash values from the same algorithm, then the timing of this function
  123. * does not reveal whether or not there is a match.
  124. *
  125. * NOTE: timing is affected if $a and $b are different lengths or either is not a
  126. * string. For the purpose of checking password hash this does not reveal information
  127. * useful to an attacker.
  128. *
  129. * @see http://blog.astrumfutura.com/2010/10/nanosecond-scale-remote-timing-attacks-on-php-applications-time-to-take-them-seriously/
  130. * @see http://codereview.stackexchange.com/questions/13512
  131. * @see https://github.com/ircmaxell/password_compat/blob/master/lib/password.php
  132. *
  133. * @param string $a First subject string to compare.
  134. * @param string $b Second subject string to compare.
  135. * @return bool true if the strings are the same, false if they are different or if
  136. * either is not a string.
  137. */
  138. public static function same($a,$b)
  139. {
  140. if(!is_string($a) || !is_string($b))
  141. return false;
  142. $mb=function_exists('mb_strlen');
  143. $length=$mb ? mb_strlen($a,'8bit') : strlen($a);
  144. if($length!==($mb ? mb_strlen($b,'8bit') : strlen($b)))
  145. return false;
  146. $check=0;
  147. for($i=0;$i<$length;$i+=1)
  148. $check|=(ord($a[$i])^ord($b[$i]));
  149. return $check===0;
  150. }
  151. /**
  152. * Generates a salt that can be used to generate a password hash.
  153. *
  154. * The PHP {@link http://php.net/manual/en/function.crypt.php crypt()} built-in function
  155. * requires, for the Blowfish hash algorithm, a salt string in a specific format:
  156. * "$2a$" (in which the "a" may be replaced by "x" or "y" see PHP manual for details),
  157. * a two digit cost parameter,
  158. * "$",
  159. * 22 characters from the alphabet "./0-9A-Za-z".
  160. *
  161. * @param int $cost Cost parameter used by the Blowfish hash algorithm.
  162. * @return string the random salt value.
  163. * @throws CException in case of invalid cost number
  164. */
  165. public static function generateSalt($cost=13)
  166. {
  167. if(!is_numeric($cost))
  168. throw new CException(Yii::t('yii','{class}::$cost must be a number.',array('{class}'=>__CLASS__)));
  169. $cost=(int)$cost;
  170. if($cost<4 || $cost>31)
  171. throw new CException(Yii::t('yii','{class}::$cost must be between 4 and 31.',array('{class}'=>__CLASS__)));
  172. if(($random=Yii::app()->getSecurityManager()->generateRandomString(22,true))===false)
  173. if(($random=Yii::app()->getSecurityManager()->generateRandomString(22,false))===false)
  174. throw new CException(Yii::t('yii','Unable to generate random string.'));
  175. return sprintf('$2a$%02d$',$cost).strtr($random,array('_'=>'.','~'=>'/'));
  176. }
  177. }