PageRenderTime 52ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/security/Password.php

https://github.com/Daikoun/lithium
PHP | 236 lines | 67 code | 22 blank | 147 comment | 11 complexity | adf6942d5c0ce4a66917dd16e30e29c4 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2012, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. namespace lithium\security;
  9. use lithium\util\String;
  10. /**
  11. * `Password` utility class that makes use of PHP's `crypt()` function. Includes a
  12. * cryptographically strong salt generator, and utility functions to hash and check
  13. * passwords.
  14. */
  15. class Password {
  16. /**
  17. * The default log2 number of iterations for Blowfish encryption.
  18. */
  19. const BF = 10;
  20. /**
  21. * The default log2 number of iterations for XDES encryption.
  22. */
  23. const XDES = 18;
  24. /**
  25. * Hashes a password using PHP's `crypt()` and an optional salt. If no
  26. * salt is supplied, a cryptographically strong salt will be generated
  27. * using `lithium\security\Password::salt()`.
  28. *
  29. * Using this function is the proper way to hash a password. Using na誰ve
  30. * methods such as sha1 or md5, as is done in many web applications, is
  31. * improper due to the lack of a cryptographically strong salt.
  32. *
  33. * Using `lithium\security\Password::hash()` ensures that:
  34. *
  35. * - Two identical passwords will never use the same salt, thus never
  36. * resulting in the same hash; this prevents a potential attacker from
  37. * compromising user accounts by using a database of most commonly used
  38. * passwords.
  39. * - The salt generator's count iterator can be increased within Lithium
  40. * or your application as computer hardware becomes faster; this results
  41. * in slower hash generation, without invalidating existing passwords.
  42. *
  43. * Usage:
  44. *
  45. * {{{
  46. * // Hash a password before storing it:
  47. * $hashed = Password::hash($password);
  48. *
  49. * // Check a password by comparing it to its hashed value:
  50. * $check = Password::check($password, $hashed);
  51. *
  52. * // Use a stronger custom salt:
  53. * $salt = Password::salt('bf', 16); // 2^16 iterations
  54. * $hashed = Password::hash($password, $salt); // Very slow
  55. * $check = Password::check($password, $hashed); // Very slow
  56. *
  57. * // Forward/backward compatibility
  58. * $salt1 = Password::salt('bf', 6);
  59. * $salt2 = Password::salt('bf', 12);
  60. * $hashed1 = Password::hash($password, $salt1); // Fast
  61. * $hashed2 = Password::hash($password, $salt2); // Slow
  62. * $check1 = Password::check($password, $hashed1); // True
  63. * $check2 = Password::check($password, $hashed2); // True
  64. * }}}
  65. *
  66. * @see lithium\security\Password::check()
  67. * @see lithium\security\Password::salt()
  68. * @link http://php.net/manual/function.crypt.php
  69. * @param string $password The password to hash.
  70. * @param string $salt Optional. The salt string.
  71. * @return string The hashed password.
  72. * The result's length will be:
  73. * - 60 chars long for Blowfish hashes
  74. * - 20 chars long for XDES hashes
  75. * - 34 chars long for MD5 hashes
  76. */
  77. public static function hash($password, $salt = null) {
  78. return crypt($password, $salt ?: static::salt());
  79. }
  80. /**
  81. * Compares a password and its hashed value using PHP's `crypt()`. Rather than a simple string
  82. * comparison, this method uses a constant-time algorithm to defend against timing attacks.
  83. *
  84. * @see lithium\security\Password::hash()
  85. * @see lithium\security\Password::salt()
  86. * @param string $password The password to check.
  87. * @param string $hash The hashed password to compare it to.
  88. * @return boolean Returns a boolean indicating whether the password is correct.
  89. */
  90. public static function check($password, $hash) {
  91. return String::compare(crypt($password, $hash), $hash);
  92. }
  93. /**
  94. * Generates a cryptographically strong salt, using the best available
  95. * method (tries Blowfish, then XDES, and fallbacks to MD5), for use in
  96. * `Password::hash()`.
  97. *
  98. * Blowfish and XDES are adaptive hashing algorithms. MD5 is not. Adaptive
  99. * hashing algorithms are designed in such a way that when computers get
  100. * faster, you can tune the algorithm to be slower by increasing the number
  101. * of hash iterations, without introducing incompatibility with existing
  102. * passwords.
  103. *
  104. * To pick an appropriate iteration count for adaptive algorithms, consider
  105. * that the original DES crypt was designed to have the speed of 4 hashes
  106. * per second on the hardware of that time. Slower than 4 hashes per second
  107. * would probably dampen usability. Faster than 100 hashes per second is
  108. * probably too fast. The defaults generate about 10 hashes per second
  109. * using a dual-core 2.2GHz CPU.
  110. *
  111. * _Note 1_: this salt generator is different from naive salt implementations
  112. * (e.g. `md5(microtime())`) in that it uses all of the available bits of
  113. * entropy for the supplied salt method.
  114. *
  115. * _Note2_: this method should not be use to generate custom salts. Indeed,
  116. * the resulting salts are prefixed with information expected by PHP's
  117. * `crypt()`. To get an arbitrarily long, cryptographically strong salt
  118. * consisting in random sequences of alpha numeric characters, use
  119. * `lithium\util\String::random()` instead.
  120. *
  121. * @link http://php.net/manual/en/function.crypt.php
  122. * @link http://www.postgresql.org/docs/9.0/static/pgcrypto.html
  123. * @see lithium\security\Password::hash()
  124. * @see lithium\security\Password::check()
  125. * @see lithium\util\String::random()
  126. * @param string $type The hash type. Optional. Defaults to the best
  127. * available option. Supported values, along with their maximum
  128. * password lengths, include:
  129. * - `'bf'`: Blowfish (128 salt bits, max 72 chars)
  130. * - `'xdes'`: XDES (24 salt bits, max 8 chars)
  131. * - `'md5'`: MD5 (48 salt bits, unlimited length)
  132. * @param integer $count Optional. The base-2 logarithm of the iteration
  133. * count, for adaptive algorithms. Defaults to:
  134. * - `10` for Blowfish
  135. * - `18` for XDES
  136. * @return string The salt string.
  137. */
  138. public static function salt($type = null, $count = null) {
  139. switch (true) {
  140. case CRYPT_BLOWFISH == 1 && (!$type || $type === 'bf'):
  141. return static::_genSaltBf($count);
  142. case CRYPT_EXT_DES == 1 && (!$type || $type === 'xdes'):
  143. return static::_genSaltXDES($count);
  144. default:
  145. return static::_genSaltMD5();
  146. }
  147. }
  148. /**
  149. * Generates a Blowfish salt for use in `lithium\security\Password::hash()`. _Note_: Does not
  150. * use the `'encode'` option of `String::random()` because it could result in 2 bits less of
  151. * entropy depending on the last character.
  152. *
  153. * @param integer $count The base-2 logarithm of the iteration count.
  154. * Defaults to `10`. Can be `4` to `31`.
  155. * @return string The Blowfish salt.
  156. */
  157. protected static function _genSaltBf($count = null) {
  158. $count = (integer) $count;
  159. $count = ($count < 4 || $count > 31) ? static::BF : $count;
  160. $base64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  161. $i = 0;
  162. $input = String::random(16);
  163. $output = '';
  164. do {
  165. $c1 = ord($input[$i++]);
  166. $output .= $base64[$c1 >> 2];
  167. $c1 = ($c1 & 0x03) << 4;
  168. if ($i >= 16) {
  169. $output .= $base64[$c1];
  170. break;
  171. }
  172. $c2 = ord($input[$i++]);
  173. $c1 |= $c2 >> 4;
  174. $output .= $base64[$c1];
  175. $c1 = ($c2 & 0x0f) << 2;
  176. $c2 = ord($input[$i++]);
  177. $c1 |= $c2 >> 6;
  178. $output .= $base64[$c1];
  179. $output .= $base64[$c2 & 0x3f];
  180. } while (1);
  181. $result = '$2a$';
  182. $result .= chr(ord('0') + $count / static::BF);
  183. $result .= chr(ord('0') + $count % static::BF);
  184. $result .= '$' . $output;
  185. return $result;
  186. }
  187. /**
  188. * Generates an Extended DES salt for use in `lithium\security\Password::hash()`.
  189. *
  190. * @param integer $count The base-2 logarithm of the iteration count. Defaults to `18`. Can be
  191. * `1` to `24`. 1 will be stripped from the non-log value, e.g. 2^18 - 1, to
  192. * ensure we don't use a weak DES key.
  193. * @return string The XDES salt.
  194. */
  195. protected static function _genSaltXDES($count = null) {
  196. $count = (integer) $count;
  197. $count = ($count < 1 || $count > 24) ? static::XDES : $count;
  198. $count = (1 << $count) - 1;
  199. $base64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  200. $output = '_' . $base64[$count & 0x3f] . $base64[($count >> 6) & 0x3f];
  201. $output .= $base64[($count >> 12) & 0x3f] . $base64[($count >> 18) & 0x3f];
  202. $output .= String::random(3, array('encode' => String::ENCODE_BASE_64));
  203. return $output;
  204. }
  205. /**
  206. * Generates an MD5 salt for use in `lithium\security\Password::hash()`.
  207. *
  208. * @return string The MD5 salt.
  209. */
  210. protected static function _genSaltMD5() {
  211. return '$1$' . String::random(6, array('encode' => String::ENCODE_BASE_64));
  212. }
  213. }
  214. ?>