No Description

password.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. /**
  3. * A Compatibility library with PHP 5.5's simplified password hashing API.
  4. *
  5. * @author Anthony Ferrara <ircmaxell@php.net>
  6. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  7. * @copyright 2012 The Authors
  8. */
  9. namespace {
  10. if (!defined('PASSWORD_BCRYPT')) {
  11. /**
  12. * PHPUnit Process isolation caches constants, but not function declarations.
  13. * So we need to check if the constants are defined separately from
  14. * the functions to enable supporting process isolation in userland
  15. * code.
  16. */
  17. define('PASSWORD_BCRYPT', 1);
  18. define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
  19. define('PASSWORD_BCRYPT_DEFAULT_COST', 10);
  20. }
  21. if (!function_exists('password_hash')) {
  22. /**
  23. * Hash the password using the specified algorithm
  24. *
  25. * @param string $password The password to hash
  26. * @param int $algo The algorithm to use (Defined by PASSWORD_* constants)
  27. * @param array $options The options for the algorithm to use
  28. *
  29. * @return string|false The hashed password, or false on error.
  30. */
  31. function password_hash($password, $algo, array $options = array()) {
  32. if (!function_exists('crypt')) {
  33. trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING);
  34. return null;
  35. }
  36. if (is_null($password) || is_int($password)) {
  37. $password = (string) $password;
  38. }
  39. if (!is_string($password)) {
  40. trigger_error("password_hash(): Password must be a string", E_USER_WARNING);
  41. return null;
  42. }
  43. if (!is_int($algo)) {
  44. trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING);
  45. return null;
  46. }
  47. $resultLength = 0;
  48. switch ($algo) {
  49. case PASSWORD_BCRYPT:
  50. $cost = PASSWORD_BCRYPT_DEFAULT_COST;
  51. if (isset($options['cost'])) {
  52. $cost = $options['cost'];
  53. if ($cost < 4 || $cost > 31) {
  54. trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
  55. return null;
  56. }
  57. }
  58. // The length of salt to generate
  59. $raw_salt_len = 16;
  60. // The length required in the final serialization
  61. $required_salt_len = 22;
  62. $hash_format = sprintf("$2y$%02d$", $cost);
  63. // The expected length of the final crypt() output
  64. $resultLength = 60;
  65. break;
  66. default:
  67. trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING);
  68. return null;
  69. }
  70. $salt_requires_encoding = false;
  71. if (isset($options['salt'])) {
  72. switch (gettype($options['salt'])) {
  73. case 'NULL':
  74. case 'boolean':
  75. case 'integer':
  76. case 'double':
  77. case 'string':
  78. $salt = (string) $options['salt'];
  79. break;
  80. case 'object':
  81. if (method_exists($options['salt'], '__tostring')) {
  82. $salt = (string) $options['salt'];
  83. break;
  84. }
  85. case 'array':
  86. case 'resource':
  87. default:
  88. trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING);
  89. return null;
  90. }
  91. if (PasswordCompat\binary\_strlen($salt) < $required_salt_len) {
  92. trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", PasswordCompat\binary\_strlen($salt), $required_salt_len), E_USER_WARNING);
  93. return null;
  94. } elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) {
  95. $salt_requires_encoding = true;
  96. }
  97. } else {
  98. $buffer = '';
  99. $buffer_valid = false;
  100. if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) {
  101. $buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM);
  102. if ($buffer) {
  103. $buffer_valid = true;
  104. }
  105. }
  106. if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) {
  107. $buffer = openssl_random_pseudo_bytes($raw_salt_len);
  108. if ($buffer) {
  109. $buffer_valid = true;
  110. }
  111. }
  112. if (!$buffer_valid && @is_readable('/dev/urandom')) {
  113. $f = fopen('/dev/urandom', 'r');
  114. $read = PasswordCompat\binary\_strlen($buffer);
  115. while ($read < $raw_salt_len) {
  116. $buffer .= fread($f, $raw_salt_len - $read);
  117. $read = PasswordCompat\binary\_strlen($buffer);
  118. }
  119. fclose($f);
  120. if ($read >= $raw_salt_len) {
  121. $buffer_valid = true;
  122. }
  123. }
  124. if (!$buffer_valid || PasswordCompat\binary\_strlen($buffer) < $raw_salt_len) {
  125. $bl = PasswordCompat\binary\_strlen($buffer);
  126. for ($i = 0; $i < $raw_salt_len; $i++) {
  127. if ($i < $bl) {
  128. $buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255));
  129. } else {
  130. $buffer .= chr(mt_rand(0, 255));
  131. }
  132. }
  133. }
  134. $salt = $buffer;
  135. $salt_requires_encoding = true;
  136. }
  137. if ($salt_requires_encoding) {
  138. // encode string with the Base64 variant used by crypt
  139. $base64_digits =
  140. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  141. $bcrypt64_digits =
  142. './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  143. $base64_string = base64_encode($salt);
  144. $salt = strtr(rtrim($base64_string, '='), $base64_digits, $bcrypt64_digits);
  145. }
  146. $salt = PasswordCompat\binary\_substr($salt, 0, $required_salt_len);
  147. $hash = $hash_format . $salt;
  148. $ret = crypt($password, $hash);
  149. if (!is_string($ret) || PasswordCompat\binary\_strlen($ret) != $resultLength) {
  150. return false;
  151. }
  152. return $ret;
  153. }
  154. /**
  155. * Get information about the password hash. Returns an array of the information
  156. * that was used to generate the password hash.
  157. *
  158. * array(
  159. * 'algo' => 1,
  160. * 'algoName' => 'bcrypt',
  161. * 'options' => array(
  162. * 'cost' => PASSWORD_BCRYPT_DEFAULT_COST,
  163. * ),
  164. * )
  165. *
  166. * @param string $hash The password hash to extract info from
  167. *
  168. * @return array The array of information about the hash.
  169. */
  170. function password_get_info($hash) {
  171. $return = array(
  172. 'algo' => 0,
  173. 'algoName' => 'unknown',
  174. 'options' => array(),
  175. );
  176. if (PasswordCompat\binary\_substr($hash, 0, 4) == '$2y$' && PasswordCompat\binary\_strlen($hash) == 60) {
  177. $return['algo'] = PASSWORD_BCRYPT;
  178. $return['algoName'] = 'bcrypt';
  179. list($cost) = sscanf($hash, "$2y$%d$");
  180. $return['options']['cost'] = $cost;
  181. }
  182. return $return;
  183. }
  184. /**
  185. * Determine if the password hash needs to be rehashed according to the options provided
  186. *
  187. * If the answer is true, after validating the password using password_verify, rehash it.
  188. *
  189. * @param string $hash The hash to test
  190. * @param int $algo The algorithm used for new password hashes
  191. * @param array $options The options array passed to password_hash
  192. *
  193. * @return boolean True if the password needs to be rehashed.
  194. */
  195. function password_needs_rehash($hash, $algo, array $options = array()) {
  196. $info = password_get_info($hash);
  197. if ($info['algo'] != $algo) {
  198. return true;
  199. }
  200. switch ($algo) {
  201. case PASSWORD_BCRYPT:
  202. $cost = isset($options['cost']) ? $options['cost'] : PASSWORD_BCRYPT_DEFAULT_COST;
  203. if ($cost != $info['options']['cost']) {
  204. return true;
  205. }
  206. break;
  207. }
  208. return false;
  209. }
  210. /**
  211. * Verify a password against a hash using a timing attack resistant approach
  212. *
  213. * @param string $password The password to verify
  214. * @param string $hash The hash to verify against
  215. *
  216. * @return boolean If the password matches the hash
  217. */
  218. function password_verify($password, $hash) {
  219. if (!function_exists('crypt')) {
  220. trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING);
  221. return false;
  222. }
  223. $ret = crypt($password, $hash);
  224. if (!is_string($ret) || PasswordCompat\binary\_strlen($ret) != PasswordCompat\binary\_strlen($hash) || PasswordCompat\binary\_strlen($ret) <= 13) {
  225. return false;
  226. }
  227. $status = 0;
  228. for ($i = 0; $i < PasswordCompat\binary\_strlen($ret); $i++) {
  229. $status |= (ord($ret[$i]) ^ ord($hash[$i]));
  230. }
  231. return $status === 0;
  232. }
  233. }
  234. }
  235. namespace PasswordCompat\binary {
  236. if (!function_exists('PasswordCompat\\binary\\_strlen')) {
  237. /**
  238. * Count the number of bytes in a string
  239. *
  240. * We cannot simply use strlen() for this, because it might be overwritten by the mbstring extension.
  241. * In this case, strlen() will count the number of *characters* based on the internal encoding. A
  242. * sequence of bytes might be regarded as a single multibyte character.
  243. *
  244. * @param string $binary_string The input string
  245. *
  246. * @internal
  247. * @return int The number of bytes
  248. */
  249. function _strlen($binary_string) {
  250. if (function_exists('mb_strlen')) {
  251. return mb_strlen($binary_string, '8bit');
  252. }
  253. return strlen($binary_string);
  254. }
  255. /**
  256. * Get a substring based on byte limits
  257. *
  258. * @see _strlen()
  259. *
  260. * @param string $binary_string The input string
  261. * @param int $start
  262. * @param int $length
  263. *
  264. * @internal
  265. * @return string The substring
  266. */
  267. function _substr($binary_string, $start, $length) {
  268. if (function_exists('mb_substr')) {
  269. return mb_substr($binary_string, $start, $length, '8bit');
  270. }
  271. return substr($binary_string, $start, $length);
  272. }
  273. /**
  274. * Check if current PHP version is compatible with the library
  275. *
  276. * @return boolean the check result
  277. */
  278. function check() {
  279. static $pass = NULL;
  280. if (is_null($pass)) {
  281. if (function_exists('crypt')) {
  282. $hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
  283. $test = crypt("password", $hash);
  284. $pass = $test == $hash;
  285. } else {
  286. $pass = false;
  287. }
  288. }
  289. return $pass;
  290. }
  291. }
  292. }