PassHash.php 29 KB

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