PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/utils/CPasswordHelper.php

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