You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

868 lines
29 KiB

  1. <?php
  2. // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
  3. namespace dokuwiki;
  4. /**
  5. * Password Hashing Class
  6. *
  7. * This class implements various mechanisms used to hash passwords
  8. *
  9. * @author Andreas Gohr <andi@splitbrain.org>
  10. * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
  11. * @license LGPL2
  12. */
  13. class PassHash
  14. {
  15. /**
  16. * Verifies a cleartext password against a crypted hash
  17. *
  18. * The method and salt used for the crypted hash is determined automatically,
  19. * then the clear text password is crypted using the same method. If both hashs
  20. * match true is is returned else false
  21. *
  22. * @author Andreas Gohr <andi@splitbrain.org>
  23. * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
  24. *
  25. * @param string $clear Clear-Text password
  26. * @param string $hash Hash to compare against
  27. * @return bool
  28. */
  29. public function verify_hash($clear, $hash)
  30. {
  31. $method = '';
  32. $salt = '';
  33. $magic = '';
  34. //determine the used method and salt
  35. if (str_starts_with($hash, 'U$')) {
  36. // This may be an updated password from user_update_7000(). Such hashes
  37. // have 'U' added as the first character and need an extra md5().
  38. $hash = substr($hash, 1);
  39. $clear = md5($clear);
  40. }
  41. $len = strlen($hash);
  42. if (preg_match('/^\$1\$([^\$]{0,8})\$/', $hash, $m)) {
  43. $method = 'smd5';
  44. $salt = $m[1];
  45. $magic = '1';
  46. } elseif (preg_match('/^\$apr1\$([^\$]{0,8})\$/', $hash, $m)) {
  47. $method = 'apr1';
  48. $salt = $m[1];
  49. $magic = 'apr1';
  50. } elseif (preg_match('/^\$S\$(.{52})$/', $hash, $m)) {
  51. $method = 'drupal_sha512';
  52. $salt = $m[1];
  53. $magic = 'S';
  54. } elseif (preg_match('/^\$P\$(.{31})$/', $hash, $m)) {
  55. $method = 'pmd5';
  56. $salt = $m[1];
  57. $magic = 'P';
  58. } elseif (preg_match('/^\$H\$(.{31})$/', $hash, $m)) {
  59. $method = 'pmd5';
  60. $salt = $m[1];
  61. $magic = 'H';
  62. } elseif (preg_match('/^pbkdf2_(\w+?)\$(\d+)\$(.{12})\$/', $hash, $m)) {
  63. $method = 'djangopbkdf2';
  64. $magic = ['algo' => $m[1], 'iter' => $m[2]];
  65. $salt = $m[3];
  66. } elseif (preg_match('/^PBKDF2(SHA\d+)\$(\d+)\$([[:xdigit:]]+)\$([[:xdigit:]]+)$/', $hash, $m)) {
  67. $method = 'seafilepbkdf2';
  68. $magic = ['algo' => $m[1], 'iter' => $m[2]];
  69. $salt = $m[3];
  70. } elseif (preg_match('/^sha1\$(.{5})\$/', $hash, $m)) {
  71. $method = 'djangosha1';
  72. $salt = $m[1];
  73. } elseif (preg_match('/^md5\$(.{5})\$/', $hash, $m)) {
  74. $method = 'djangomd5';
  75. $salt = $m[1];
  76. } elseif (preg_match('/^\$2(a|y)\$(.{2})\$/', $hash, $m)) {
  77. $method = 'bcrypt';
  78. $salt = $hash;
  79. } elseif (str_starts_with($hash, '{SSHA}')) {
  80. $method = 'ssha';
  81. $salt = substr(base64_decode(substr($hash, 6)), 20);
  82. } elseif (str_starts_with($hash, '{SMD5}')) {
  83. $method = 'lsmd5';
  84. $salt = substr(base64_decode(substr($hash, 6)), 16);
  85. } elseif (preg_match('/^:B:(.+?):.{32}$/', $hash, $m)) {
  86. $method = 'mediawiki';
  87. $salt = $m[1];
  88. } elseif (preg_match('/^\$(5|6)\$(rounds=\d+)?\$?(.+?)\$/', $hash, $m)) {
  89. $method = 'sha2';
  90. $salt = $m[3];
  91. $magic = ['prefix' => $m[1], 'rounds' => $m[2]];
  92. } elseif (preg_match('/^\$(argon2id?)/', $hash, $m)) {
  93. if (!defined('PASSWORD_' . strtoupper($m[1]))) {
  94. throw new \Exception('This PHP installation has no ' . strtoupper($m[1]) . ' support');
  95. }
  96. return password_verify($clear, $hash);
  97. } elseif ($len == 32) {
  98. $method = 'md5';
  99. } elseif ($len == 40) {
  100. $method = 'sha1';
  101. } elseif ($len == 16) {
  102. $method = 'mysql';
  103. } elseif ($len == 41 && $hash[0] == '*') {
  104. $method = 'my411';
  105. } elseif ($len == 34) {
  106. $method = 'kmd5';
  107. $salt = $hash;
  108. } else {
  109. $method = 'crypt';
  110. $salt = substr($hash, 0, 2);
  111. }
  112. //crypt and compare
  113. $call = 'hash_' . $method;
  114. $newhash = $this->$call($clear, $salt, $magic);
  115. if (\hash_equals($newhash, $hash)) {
  116. return true;
  117. }
  118. return false;
  119. }
  120. /**
  121. * Create a random salt
  122. *
  123. * @param int $len The length of the salt
  124. * @return string
  125. */
  126. public function gen_salt($len = 32)
  127. {
  128. $salt = '';
  129. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  130. for ($i = 0; $i < $len; $i++) {
  131. $salt .= $chars[$this->random(0, 61)];
  132. }
  133. return $salt;
  134. }
  135. /**
  136. * Initialize the passed variable with a salt if needed.
  137. *
  138. * If $salt is not null, the value is kept, but the lenght restriction is
  139. * applied (unless, $cut is false).
  140. *
  141. * @param string|null &$salt The salt, pass null if you want one generated
  142. * @param int $len The length of the salt
  143. * @param bool $cut Apply length restriction to existing salt?
  144. */
  145. public function init_salt(&$salt, $len = 32, $cut = true)
  146. {
  147. if (is_null($salt)) {
  148. $salt = $this->gen_salt($len);
  149. $cut = true; // for new hashes we alway apply length restriction
  150. }
  151. if (strlen($salt) > $len && $cut) $salt = substr($salt, 0, $len);
  152. }
  153. // Password hashing methods follow below
  154. /**
  155. * Password hashing method 'smd5'
  156. *
  157. * Uses salted MD5 hashs. Salt is 8 bytes long.
  158. *
  159. * The same mechanism is used by Apache's 'apr1' method. This will
  160. * fallback to a implementation in pure PHP if MD5 support is not
  161. * available in crypt()
  162. *
  163. * @author Andreas Gohr <andi@splitbrain.org>
  164. * @author <mikey_nich at hotmail dot com>
  165. * @link http://php.net/manual/en/function.crypt.php#73619
  166. *
  167. * @param string $clear The clear text to hash
  168. * @param string $salt The salt to use, null for random
  169. * @return string Hashed password
  170. */
  171. public function hash_smd5($clear, $salt = null)
  172. {
  173. $this->init_salt($salt, 8);
  174. if (defined('CRYPT_MD5') && CRYPT_MD5 && $salt !== '') {
  175. return crypt($clear, '$1$' . $salt . '$');
  176. } else {
  177. // Fall back to PHP-only implementation
  178. return $this->hash_apr1($clear, $salt, '1');
  179. }
  180. }
  181. /**
  182. * Password hashing method 'lsmd5'
  183. *
  184. * Uses salted MD5 hashs. Salt is 8 bytes long.
  185. *
  186. * This is the format used by LDAP.
  187. *
  188. * @param string $clear The clear text to hash
  189. * @param string $salt The salt to use, null for random
  190. * @return string Hashed password
  191. */
  192. public function hash_lsmd5($clear, $salt = null)
  193. {
  194. $this->init_salt($salt, 8);
  195. return "{SMD5}" . base64_encode(md5($clear . $salt, true) . $salt);
  196. }
  197. /**
  198. * Password hashing method 'apr1'
  199. *
  200. * Uses salted MD5 hashs. Salt is 8 bytes long.
  201. *
  202. * This is basically the same as smd1 above, but as used by Apache.
  203. *
  204. * @author <mikey_nich at hotmail dot com>
  205. * @link http://php.net/manual/en/function.crypt.php#73619
  206. *
  207. * @param string $clear The clear text to hash
  208. * @param string $salt The salt to use, null for random
  209. * @param string $magic The hash identifier (apr1 or 1)
  210. * @return string Hashed password
  211. */
  212. public function hash_apr1($clear, $salt = null, $magic = 'apr1')
  213. {
  214. $this->init_salt($salt, 8);
  215. $len = strlen($clear);
  216. $text = $clear . '$' . $magic . '$' . $salt;
  217. $bin = pack("H32", md5($clear . $salt . $clear));
  218. for ($i = $len; $i > 0; $i -= 16) {
  219. $text .= substr($bin, 0, min(16, $i));
  220. }
  221. for ($i = $len; $i > 0; $i >>= 1) {
  222. $text .= ($i & 1) ? chr(0) : $clear[0];
  223. }
  224. $bin = pack("H32", md5($text));
  225. for ($i = 0; $i < 1000; $i++) {
  226. $new = ($i & 1) ? $clear : $bin;
  227. if ($i % 3) $new .= $salt;
  228. if ($i % 7) $new .= $clear;
  229. $new .= ($i & 1) ? $bin : $clear;
  230. $bin = pack("H32", md5($new));
  231. }
  232. $tmp = '';
  233. for ($i = 0; $i < 5; $i++) {
  234. $k = $i + 6;
  235. $j = $i + 12;
  236. if ($j == 16) $j = 5;
  237. $tmp = $bin[$i] . $bin[$k] . $bin[$j] . $tmp;
  238. }
  239. $tmp = chr(0) . chr(0) . $bin[11] . $tmp;
  240. $tmp = strtr(
  241. strrev(substr(base64_encode($tmp), 2)),
  242. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
  243. "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  244. );
  245. return '$' . $magic . '$' . $salt . '$' . $tmp;
  246. }
  247. /**
  248. * Password hashing method 'md5'
  249. *
  250. * Uses MD5 hashs.
  251. *
  252. * @param string $clear The clear text to hash
  253. * @return string Hashed password
  254. */
  255. public function hash_md5($clear)
  256. {
  257. return md5($clear);
  258. }
  259. /**
  260. * Password hashing method 'sha1'
  261. *
  262. * Uses SHA1 hashs.
  263. *
  264. * @param string $clear The clear text to hash
  265. * @return string Hashed password
  266. */
  267. public function hash_sha1($clear)
  268. {
  269. return sha1($clear);
  270. }
  271. /**
  272. * Password hashing method 'ssha' as used by LDAP
  273. *
  274. * Uses salted SHA1 hashs. Salt is 4 bytes long.
  275. *
  276. * @param string $clear The clear text to hash
  277. * @param string $salt The salt to use, null for random
  278. * @return string Hashed password
  279. */
  280. public function hash_ssha($clear, $salt = null)
  281. {
  282. $this->init_salt($salt, 4);
  283. return '{SSHA}' . base64_encode(pack("H*", sha1($clear . $salt)) . $salt);
  284. }
  285. /**
  286. * Password hashing method 'crypt'
  287. *
  288. * Uses salted crypt hashs. Salt is 2 bytes long.
  289. *
  290. * @param string $clear The clear text to hash
  291. * @param string $salt The salt to use, null for random
  292. * @return string Hashed password
  293. */
  294. public function hash_crypt($clear, $salt = null)
  295. {
  296. $this->init_salt($salt, 2);
  297. return crypt($clear, $salt);
  298. }
  299. /**
  300. * Password hashing method 'mysql'
  301. *
  302. * This method was used by old MySQL systems
  303. *
  304. * @link http://php.net/mysql
  305. * @author <soren at byu dot edu>
  306. * @param string $clear The clear text to hash
  307. * @return string Hashed password
  308. */
  309. public function hash_mysql($clear)
  310. {
  311. $nr = 0x50305735;
  312. $nr2 = 0x12345671;
  313. $add = 7;
  314. $charArr = preg_split("//", $clear);
  315. foreach ($charArr as $char) {
  316. if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
  317. $charVal = ord($char);
  318. $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
  319. $nr2 += ($nr2 << 8) ^ $nr;
  320. $add += $charVal;
  321. }
  322. return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
  323. }
  324. /**
  325. * Password hashing method 'my411'
  326. *
  327. * Uses SHA1 hashs. This method is used by MySQL 4.11 and above
  328. *
  329. * @param string $clear The clear text to hash
  330. * @return string Hashed password
  331. */
  332. public function hash_my411($clear)
  333. {
  334. return '*' . strtoupper(sha1(pack("H*", sha1($clear))));
  335. }
  336. /**
  337. * Password hashing method 'kmd5'
  338. *
  339. * Uses salted MD5 hashs.
  340. *
  341. * Salt is 2 bytes long, but stored at position 16, so you need to pass at
  342. * least 18 bytes. You can pass the crypted hash as salt.
  343. *
  344. * @param string $clear The clear text to hash
  345. * @param string $salt The salt to use, null for random
  346. * @return string Hashed password
  347. */
  348. public function hash_kmd5($clear, $salt = null)
  349. {
  350. $this->init_salt($salt);
  351. $key = substr($salt, 16, 2);
  352. $hash1 = strtolower(md5($key . md5($clear)));
  353. $hash2 = substr($hash1, 0, 16) . $key . substr($hash1, 16);
  354. return $hash2;
  355. }
  356. /**
  357. * Password stretched hashing wrapper.
  358. *
  359. * Initial hash is repeatedly rehashed with same password.
  360. * Any salted hash algorithm supported by PHP hash() can be used. Salt
  361. * is 1+8 bytes long, 1st byte is the iteration count when given. For null
  362. * salts $compute is used.
  363. *
  364. * The actual iteration count is 2 to the power of the given count,
  365. * maximum is 30 (-> 2^30 = 1_073_741_824). If a higher one is given,
  366. * the function throws an exception.
  367. * This iteration count is expected to grow with increasing power of
  368. * new computers.
  369. *
  370. * @author Andreas Gohr <andi@splitbrain.org>
  371. * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
  372. * @link http://www.openwall.com/phpass/
  373. *
  374. * @param string $algo The hash algorithm to be used
  375. * @param string $clear The clear text to hash
  376. * @param string $salt The salt to use, null for random
  377. * @param string $magic The hash identifier (P or H)
  378. * @param int $compute The iteration count for new passwords
  379. * @throws \Exception
  380. * @return string Hashed password
  381. */
  382. protected function stretched_hash($algo, $clear, $salt = null, $magic = 'P', $compute = 8)
  383. {
  384. $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  385. if (is_null($salt)) {
  386. $this->init_salt($salt);
  387. $salt = $itoa64[$compute] . $salt; // prefix iteration count
  388. }
  389. $iterc = $salt[0]; // pos 0 of salt is log2(iteration count)
  390. $iter = strpos($itoa64, $iterc);
  391. if ($iter > 30) {
  392. throw new \Exception("Too high iteration count ($iter) in " .
  393. self::class . '::' . __FUNCTION__);
  394. }
  395. $iter = 1 << $iter;
  396. $salt = substr($salt, 1, 8);
  397. // iterate
  398. $hash = hash($algo, $salt . $clear, true);
  399. do {
  400. $hash = hash($algo, $hash . $clear, true);
  401. } while (--$iter);
  402. // encode
  403. $output = '';
  404. $count = strlen($hash);
  405. $i = 0;
  406. do {
  407. $value = ord($hash[$i++]);
  408. $output .= $itoa64[$value & 0x3f];
  409. if ($i < $count)
  410. $value |= ord($hash[$i]) << 8;
  411. $output .= $itoa64[($value >> 6) & 0x3f];
  412. if ($i++ >= $count)
  413. break;
  414. if ($i < $count)
  415. $value |= ord($hash[$i]) << 16;
  416. $output .= $itoa64[($value >> 12) & 0x3f];
  417. if ($i++ >= $count)
  418. break;
  419. $output .= $itoa64[($value >> 18) & 0x3f];
  420. } while ($i < $count);
  421. return '$' . $magic . '$' . $iterc . $salt . $output;
  422. }
  423. /**
  424. * Password hashing method 'pmd5'
  425. *
  426. * Repeatedly uses salted MD5 hashs. See stretched_hash() for the
  427. * details.
  428. *
  429. *
  430. * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
  431. * @link http://www.openwall.com/phpass/
  432. * @see PassHash::stretched_hash() for the implementation details.
  433. *
  434. * @param string $clear The clear text to hash
  435. * @param string $salt The salt to use, null for random
  436. * @param string $magic The hash identifier (P or H)
  437. * @param int $compute The iteration count for new passwords
  438. * @throws Exception
  439. * @return string Hashed password
  440. */
  441. public function hash_pmd5($clear, $salt = null, $magic = 'P', $compute = 8)
  442. {
  443. return $this->stretched_hash('md5', $clear, $salt, $magic, $compute);
  444. }
  445. /**
  446. * Password hashing method 'drupal_sha512'
  447. *
  448. * Implements Drupal salted sha512 hashs. Drupal truncates the hash at 55
  449. * characters. See stretched_hash() for the details;
  450. *
  451. * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
  452. * @link https://api.drupal.org/api/drupal/includes%21password.inc/7.x
  453. * @see PassHash::stretched_hash() for the implementation details.
  454. *
  455. * @param string $clear The clear text to hash
  456. * @param string $salt The salt to use, null for random
  457. * @param string $magic The hash identifier (S)
  458. * @param int $compute The iteration count for new passwords (defautl is drupal 7's)
  459. * @throws Exception
  460. * @return string Hashed password
  461. */
  462. public function hash_drupal_sha512($clear, $salt = null, $magic = 'S', $compute = 15)
  463. {
  464. return substr($this->stretched_hash('sha512', $clear, $salt, $magic, $compute), 0, 55);
  465. }
  466. /**
  467. * Alias for hash_pmd5
  468. *
  469. * @param string $clear
  470. * @param null|string $salt
  471. * @param string $magic
  472. * @param int $compute
  473. *
  474. * @return string
  475. * @throws \Exception
  476. */
  477. public function hash_hmd5($clear, $salt = null, $magic = 'H', $compute = 8)
  478. {
  479. return $this->hash_pmd5($clear, $salt, $magic, $compute);
  480. }
  481. /**
  482. * Password hashing method 'djangosha1'
  483. *
  484. * Uses salted SHA1 hashs. Salt is 5 bytes long.
  485. * This is used by the Django Python framework
  486. *
  487. * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords
  488. *
  489. * @param string $clear The clear text to hash
  490. * @param string $salt The salt to use, null for random
  491. * @return string Hashed password
  492. */
  493. public function hash_djangosha1($clear, $salt = null)
  494. {
  495. $this->init_salt($salt, 5);
  496. return 'sha1$' . $salt . '$' . sha1($salt . $clear);
  497. }
  498. /**
  499. * Password hashing method 'djangomd5'
  500. *
  501. * Uses salted MD5 hashs. Salt is 5 bytes long.
  502. * This is used by the Django Python framework
  503. *
  504. * @link http://docs.djangoproject.com/en/dev/topics/auth/#passwords
  505. *
  506. * @param string $clear The clear text to hash
  507. * @param string $salt The salt to use, null for random
  508. * @return string Hashed password
  509. */
  510. public function hash_djangomd5($clear, $salt = null)
  511. {
  512. $this->init_salt($salt, 5);
  513. return 'md5$' . $salt . '$' . md5($salt . $clear);
  514. }
  515. /**
  516. * Password hashing method 'seafilepbkdf2'
  517. *
  518. * An algorithm and iteration count should be given in the opts array.
  519. *
  520. * Hash algorithm is the string that is in the password string in seafile
  521. * database. It has to be converted to a php algo name.
  522. *
  523. * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
  524. * @see https://stackoverflow.com/a/23670177
  525. *
  526. * @param string $clear The clear text to hash
  527. * @param string $salt The salt to use, null for random
  528. * @param array $opts ('algo' => hash algorithm, 'iter' => iterations)
  529. * @return string Hashed password
  530. * @throws Exception when PHP is missing support for the method/algo
  531. */
  532. public function hash_seafilepbkdf2($clear, $salt = null, $opts = [])
  533. {
  534. $this->init_salt($salt, 64);
  535. if (empty($opts['algo'])) {
  536. $prefixalgo = 'SHA256';
  537. } else {
  538. $prefixalgo = $opts['algo'];
  539. }
  540. $algo = strtolower($prefixalgo);
  541. if (empty($opts['iter'])) {
  542. $iter = 10000;
  543. } else {
  544. $iter = (int) $opts['iter'];
  545. }
  546. if (!function_exists('hash_pbkdf2')) {
  547. throw new Exception('This PHP installation has no PBKDF2 support');
  548. }
  549. if (!in_array($algo, hash_algos())) {
  550. throw new Exception("This PHP installation has no $algo support");
  551. }
  552. $hash = hash_pbkdf2($algo, $clear, hex2bin($salt), $iter, 0);
  553. return "PBKDF2$prefixalgo\$$iter\$$salt\$$hash";
  554. }
  555. /**
  556. * Password hashing method 'djangopbkdf2'
  557. *
  558. * An algorithm and iteration count should be given in the opts array.
  559. * Defaults to sha256 and 24000 iterations
  560. *
  561. * @param string $clear The clear text to hash
  562. * @param string $salt The salt to use, null for random
  563. * @param array $opts ('algo' => hash algorithm, 'iter' => iterations)
  564. * @return string Hashed password
  565. * @throws \Exception when PHP is missing support for the method/algo
  566. */
  567. public function hash_djangopbkdf2($clear, $salt = null, $opts = [])
  568. {
  569. $this->init_salt($salt, 12);
  570. if (empty($opts['algo'])) {
  571. $algo = 'sha256';
  572. } else {
  573. $algo = $opts['algo'];
  574. }
  575. if (empty($opts['iter'])) {
  576. $iter = 24000;
  577. } else {
  578. $iter = (int) $opts['iter'];
  579. }
  580. if (!function_exists('hash_pbkdf2')) {
  581. throw new \Exception('This PHP installation has no PBKDF2 support');
  582. }
  583. if (!in_array($algo, hash_algos())) {
  584. throw new \Exception("This PHP installation has no $algo support");
  585. }
  586. $hash = base64_encode(hash_pbkdf2($algo, $clear, $salt, $iter, 0, true));
  587. return "pbkdf2_$algo\$$iter\$$salt\$$hash";
  588. }
  589. /**
  590. * Alias for djangopbkdf2 defaulting to sha256 as hash algorithm
  591. *
  592. * @param string $clear The clear text to hash
  593. * @param string $salt The salt to use, null for random
  594. * @param array $opts ('iter' => iterations)
  595. * @return string Hashed password
  596. * @throws \Exception when PHP is missing support for the method/algo
  597. */
  598. public function hash_djangopbkdf2_sha256($clear, $salt = null, $opts = [])
  599. {
  600. $opts['algo'] = 'sha256';
  601. return $this->hash_djangopbkdf2($clear, $salt, $opts);
  602. }
  603. /**
  604. * Alias for djangopbkdf2 defaulting to sha1 as hash algorithm
  605. *
  606. * @param string $clear The clear text to hash
  607. * @param string $salt The salt to use, null for random
  608. * @param array $opts ('iter' => iterations)
  609. * @return string Hashed password
  610. * @throws \Exception when PHP is missing support for the method/algo
  611. */
  612. public function hash_djangopbkdf2_sha1($clear, $salt = null, $opts = [])
  613. {
  614. $opts['algo'] = 'sha1';
  615. return $this->hash_djangopbkdf2($clear, $salt, $opts);
  616. }
  617. /**
  618. * Passwordhashing method 'bcrypt'
  619. *
  620. * Uses a modified blowfish algorithm called eksblowfish
  621. * This method works on PHP 5.3+ only and will throw an exception
  622. * if the needed crypt support isn't available
  623. *
  624. * A full hash should be given as salt (starting with $a2$) or this
  625. * will break. When no salt is given, the iteration count can be set
  626. * through the $compute variable.
  627. *
  628. * @param string $clear The clear text to hash
  629. * @param string $salt The salt to use, null for random
  630. * @param int $compute The iteration count (between 4 and 31)
  631. * @throws \Exception
  632. * @return string Hashed password
  633. */
  634. public function hash_bcrypt($clear, $salt = null, $compute = 10)
  635. {
  636. if (!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH !== 1) {
  637. throw new \Exception('This PHP installation has no bcrypt support');
  638. }
  639. if (is_null($salt)) {
  640. if ($compute < 4 || $compute > 31) $compute = 8;
  641. $salt = '$2y$' . str_pad($compute, 2, '0', STR_PAD_LEFT) . '$' .
  642. $this->gen_salt(22);
  643. }
  644. return crypt($clear, $salt);
  645. }
  646. /**
  647. * Password hashing method SHA-2
  648. *
  649. * This is only supported on PHP 5.3.2 or higher and will throw an exception if
  650. * the needed crypt support is not available
  651. *
  652. * Uses:
  653. * - SHA-2 with 256-bit output for prefix $5$
  654. * - SHA-2 with 512-bit output for prefix $6$ (default)
  655. *
  656. * @param string $clear The clear text to hash
  657. * @param string $salt The salt to use, null for random
  658. * @param array $opts ('rounds' => rounds for sha256/sha512, 'prefix' => selected method from SHA-2 family)
  659. * @return string Hashed password
  660. * @throws \Exception
  661. */
  662. public function hash_sha2($clear, $salt = null, $opts = [])
  663. {
  664. if (empty($opts['prefix'])) {
  665. $prefix = '6';
  666. } else {
  667. $prefix = $opts['prefix'];
  668. }
  669. if (empty($opts['rounds'])) {
  670. $rounds = null;
  671. } else {
  672. $rounds = $opts['rounds'];
  673. }
  674. if ($prefix == '5' && (!defined('CRYPT_SHA256') || CRYPT_SHA256 !== 1)) {
  675. throw new \Exception('This PHP installation has no SHA256 support');
  676. }
  677. if ($prefix == '6' && (!defined('CRYPT_SHA512') || CRYPT_SHA512 !== 1)) {
  678. throw new \Exception('This PHP installation has no SHA512 support');
  679. }
  680. $this->init_salt($salt, 8, false);
  681. if (empty($rounds)) {
  682. return crypt($clear, '$' . $prefix . '$' . $salt . '$');
  683. } else {
  684. return crypt($clear, '$' . $prefix . '$' . $rounds . '$' . $salt . '$');
  685. }
  686. }
  687. /** @see sha2 */
  688. public function hash_sha512($clear, $salt = null, $opts = [])
  689. {
  690. $opts['prefix'] = 6;
  691. return $this->hash_sha2($clear, $salt, $opts);
  692. }
  693. /** @see sha2 */
  694. public function hash_sha256($clear, $salt = null, $opts = [])
  695. {
  696. $opts['prefix'] = 5;
  697. return $this->hash_sha2($clear, $salt, $opts);
  698. }
  699. /**
  700. * Password hashing method 'mediawiki'
  701. *
  702. * Uses salted MD5, this is referred to as Method B in MediaWiki docs. Unsalted md5
  703. * method 'A' is not supported.
  704. *
  705. * @link http://www.mediawiki.org/wiki/Manual_talk:User_table#user_password_column
  706. *
  707. * @param string $clear The clear text to hash
  708. * @param string $salt The salt to use, null for random
  709. * @return string Hashed password
  710. */
  711. public function hash_mediawiki($clear, $salt = null)
  712. {
  713. $this->init_salt($salt, 8, false);
  714. return ':B:' . $salt . ':' . md5($salt . '-' . md5($clear));
  715. }
  716. /**
  717. * Password hashing method 'argon2i'
  718. *
  719. * Uses php's own password_hash function to create argon2i password hash
  720. * Default Cost and thread options are used for now.
  721. *
  722. * @link https://www.php.net/manual/de/function.password-hash.php
  723. *
  724. * @param string $clear The clear text to hash
  725. * @return string Hashed password
  726. */
  727. public function hash_argon2i($clear)
  728. {
  729. if (!defined('PASSWORD_ARGON2I')) {
  730. throw new \Exception('This PHP installation has no ARGON2I support');
  731. }
  732. return password_hash($clear, PASSWORD_ARGON2I);
  733. }
  734. /**
  735. * Password hashing method 'argon2id'
  736. *
  737. * Uses php's own password_hash function to create argon2id password hash
  738. * Default Cost and thread options are used for now.
  739. *
  740. * @link https://www.php.net/manual/de/function.password-hash.php
  741. *
  742. * @param string $clear The clear text to hash
  743. * @return string Hashed password
  744. */
  745. public function hash_argon2id($clear)
  746. {
  747. if (!defined('PASSWORD_ARGON2ID')) {
  748. throw new \Exception('This PHP installation has no ARGON2ID support');
  749. }
  750. return password_hash($clear, PASSWORD_ARGON2ID);
  751. }
  752. /**
  753. * Wraps around native hash_hmac() or reimplents it
  754. *
  755. * This is not directly used as password hashing method, and thus isn't callable via the
  756. * verify_hash() method. It should be used to create signatures and might be used in other
  757. * password hashing methods.
  758. *
  759. * @see hash_hmac()
  760. * @author KC Cloyd
  761. * @link http://php.net/manual/en/function.hash-hmac.php#93440
  762. *
  763. * @param string $algo Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4",
  764. * etc..) See hash_algos() for a list of supported algorithms.
  765. * @param string $data Message to be hashed.
  766. * @param string $key Shared secret key used for generating the HMAC variant of the message digest.
  767. * @param bool $raw_output When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.
  768. * @return string
  769. */
  770. public static function hmac($algo, $data, $key, $raw_output = false)
  771. {
  772. // use native function if available and not in unit test
  773. if (function_exists('hash_hmac') && !defined('SIMPLE_TEST')) {
  774. return hash_hmac($algo, $data, $key, $raw_output);
  775. }
  776. $algo = strtolower($algo);
  777. $pack = 'H' . strlen($algo('test'));
  778. $size = 64;
  779. $opad = str_repeat(chr(0x5C), $size);
  780. $ipad = str_repeat(chr(0x36), $size);
  781. if (strlen($key) > $size) {
  782. $key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
  783. } else {
  784. $key = str_pad($key, $size, chr(0x00));
  785. }
  786. for ($i = 0; $i < strlen($key) - 1; $i++) {
  787. $ochar = $opad[$i] ^ $key[$i];
  788. $ichar = $ipad[$i] ^ $key[$i];
  789. $opad[$i] = $ochar;
  790. $ipad[$i] = $ichar;
  791. }
  792. $output = $algo($opad . pack($pack, $algo($ipad . $data)));
  793. return ($raw_output) ? pack($pack, $output) : $output;
  794. }
  795. /**
  796. * Use a secure random generator
  797. *
  798. * @param int $min
  799. * @param int $max
  800. * @return int
  801. */
  802. protected function random($min, $max)
  803. {
  804. try {
  805. return random_int($min, $max);
  806. } catch (\Exception $e) {
  807. // availability of random source is checked elsewhere in DokuWiki
  808. // we demote this to an unchecked runtime exception here
  809. throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);
  810. }
  811. }
  812. }