Hash.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. <?php
  2. /**
  3. * Wrapper around hash() and hash_hmac() functions supporting truncated hashes
  4. * such as sha256-96. Any hash algorithm returned by hash_algos() (and
  5. * truncated versions thereof) are supported.
  6. *
  7. * If {@link self::setKey() setKey()} is called, {@link self::hash() hash()} will
  8. * return the HMAC as opposed to the hash.
  9. *
  10. * Here's a short example of how to use this library:
  11. * <code>
  12. * <?php
  13. * include 'vendor/autoload.php';
  14. *
  15. * $hash = new \phpseclib\Crypt\Hash('sha512');
  16. *
  17. * $hash->setKey('abcdefg');
  18. *
  19. * echo base64_encode($hash->hash('abcdefg'));
  20. * ?>
  21. * </code>
  22. *
  23. * @category Crypt
  24. * @package Hash
  25. * @author Jim Wigginton <terrafrost@php.net>
  26. * @copyright 2015 Jim Wigginton
  27. * @author Andreas Fischer <bantu@phpbb.com>
  28. * @copyright 2015 Andreas Fischer
  29. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  30. * @link http://phpseclib.sourceforge.net
  31. */
  32. namespace phpseclib\Crypt;
  33. use phpseclib\Math\BigInteger;
  34. use phpseclib\Exception\UnsupportedAlgorithmException;
  35. use phpseclib\Common\Functions\Strings;
  36. /**
  37. * @package Hash
  38. * @author Jim Wigginton <terrafrost@php.net>
  39. * @author Andreas Fischer <bantu@phpbb.com>
  40. * @access public
  41. */
  42. class Hash
  43. {
  44. /**
  45. * Hash Parameter
  46. *
  47. * @see self::setHash()
  48. * @var int
  49. * @access private
  50. */
  51. private $hashParam;
  52. /**
  53. * Byte-length of hash output (Internal HMAC)
  54. *
  55. * @see self::setHash()
  56. * @var int
  57. * @access private
  58. */
  59. private $length;
  60. /**
  61. * Hash Algorithm
  62. *
  63. * @see self::setHash()
  64. * @var string
  65. * @access private
  66. */
  67. private $hash;
  68. /**
  69. * Key
  70. *
  71. * @see self::setKey()
  72. * @var string
  73. * @access private
  74. */
  75. private $key = false;
  76. /**
  77. * Initial Hash
  78. *
  79. * Used only for sha512/*
  80. *
  81. * @see self::_sha512()
  82. * @var array
  83. * @access private
  84. */
  85. private $initial = false;
  86. /**
  87. * Outer XOR (Internal HMAC)
  88. *
  89. * Used only for sha512/*
  90. *
  91. * @see self::hash()
  92. * @var string
  93. * @access private
  94. */
  95. private $opad;
  96. /**
  97. * Inner XOR (Internal HMAC)
  98. *
  99. * Used only for sha512/*
  100. *
  101. * @see self::hash()
  102. * @var string
  103. * @access private
  104. */
  105. private $ipad;
  106. /**
  107. * Default Constructor.
  108. *
  109. * @param string $hash
  110. * @access public
  111. */
  112. public function __construct($hash = 'sha256')
  113. {
  114. $this->setHash($hash);
  115. $this->ipad = str_repeat(chr(0x36), 128);
  116. $this->opad = str_repeat(chr(0x5C), 128);
  117. }
  118. /**
  119. * Sets the key for HMACs
  120. *
  121. * Keys can be of any length.
  122. *
  123. * @access public
  124. * @param string $key
  125. */
  126. public function setKey($key = false)
  127. {
  128. $this->key = $key;
  129. }
  130. /**
  131. * Gets the hash function.
  132. *
  133. * As set by the constructor or by the setHash() method.
  134. *
  135. * @access public
  136. * @return string
  137. */
  138. public function getHash()
  139. {
  140. return $this->hashParam;
  141. }
  142. /**
  143. * Sets the hash function.
  144. *
  145. * @access public
  146. * @param string $hash
  147. */
  148. public function setHash($hash)
  149. {
  150. $this->hashParam = $hash = strtolower($hash);
  151. switch ($hash) {
  152. case 'md2-96':
  153. case 'md5-96':
  154. case 'sha1-96':
  155. case 'sha224-96':
  156. case 'sha256-96':
  157. case 'sha384-96':
  158. case 'sha512-96':
  159. case 'sha512/224-96':
  160. case 'sha512/256-96':
  161. $hash = substr($hash, 0, -3);
  162. $this->length = 12; // 96 / 8 = 12
  163. break;
  164. case 'md2':
  165. case 'md5':
  166. $this->length = 16;
  167. break;
  168. case 'sha1':
  169. $this->length = 20;
  170. break;
  171. case 'sha224':
  172. case 'sha512/224':
  173. $this->length = 28;
  174. break;
  175. case 'sha256':
  176. case 'sha512/256':
  177. $this->length = 32;
  178. break;
  179. case 'sha384':
  180. $this->length = 48;
  181. break;
  182. case 'sha512':
  183. $this->length = 64;
  184. break;
  185. default:
  186. throw new UnsupportedAlgorithmException(
  187. "$hash is not a supported algorithm"
  188. );
  189. }
  190. switch ($hash) {
  191. case 'md2-96':
  192. case 'md5-96':
  193. case 'sha1-96':
  194. case 'sha224-96':
  195. case 'sha256-96':
  196. case 'md2':
  197. case 'md5':
  198. case 'sha1':
  199. case 'sha224':
  200. case 'sha256':
  201. $this->blockSize = 512;
  202. break;
  203. default:
  204. $this->blockSize = 1024;
  205. }
  206. if ($hash == 'sha512/224' || $hash == 'sha512/256') {
  207. // from http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf#page=24
  208. $this->initial = $hash == 'sha512/256' ?
  209. array(
  210. '22312194FC2BF72C', '9F555FA3C84C64C2', '2393B86B6F53B151', '963877195940EABD',
  211. '96283EE2A88EFFE3', 'BE5E1E2553863992', '2B0199FC2C85B8AA', '0EB72DDC81C52CA2'
  212. ) :
  213. array(
  214. '8C3D37C819544DA2', '73E1996689DCD4D6', '1DFAB7AE32FF9C82', '679DD514582F9FCF',
  215. '0F6D2B697BD44DA8', '77E36F7304C48942', '3F9D85A86A1D36C8', '1112E6AD91D692A1'
  216. );
  217. for ($i = 0; $i < 8; $i++) {
  218. $this->initial[$i] = new BigInteger($this->initial[$i], 16);
  219. $this->initial[$i]->setPrecision(64);
  220. }
  221. }
  222. $this->hash = $hash;
  223. }
  224. /**
  225. * Compute the HMAC.
  226. *
  227. * @access public
  228. * @param string $text
  229. * @return string
  230. */
  231. public function hash($text)
  232. {
  233. switch ($this->hash) {
  234. case 'sha512/224':
  235. case 'sha512/256':
  236. if (empty($this->key) || !is_string($this->key)) {
  237. return substr(self::_sha512($text, $this->initial), 0, $this->length);
  238. }
  239. /* "Applications that use keys longer than B bytes will first hash the key using H and then use the
  240. resultant L byte string as the actual key to HMAC."
  241. -- http://tools.ietf.org/html/rfc2104#section-2 */
  242. $key = strlen($this->key) > $this->b ? self::_sha512($this->key, $this->initial) : $this->key;
  243. $key = str_pad($this->key, 128, chr(0)); // step 1
  244. $temp = $this->ipad ^ $this->key; // step 2
  245. $temp .= $text; // step 3
  246. $temp = self::_sha512($temp, $this->initial); // step 4
  247. $output = $this->opad ^ $this->key; // step 5
  248. $output.= $temp; // step 6
  249. $output = self::_sha512($output, $this->initial); // step 7
  250. return substr($output, 0, $this->length);
  251. }
  252. $output = !empty($this->key) || is_string($this->key) ?
  253. hash_hmac($this->hash, $text, $this->key, true) :
  254. hash($this->hash, $text, true);
  255. return strlen($output) > $this->length
  256. ? substr($output, 0, $this->length)
  257. : $output;
  258. }
  259. /**
  260. * Returns the hash length (in bits)
  261. *
  262. * @access public
  263. * @return int
  264. */
  265. public function getLength()
  266. {
  267. return $this->length << 3;
  268. }
  269. /**
  270. * Returns the hash length (in bytes)
  271. *
  272. * @access public
  273. * @return int
  274. */
  275. public function getLengthInBytes()
  276. {
  277. return $this->length;
  278. }
  279. /**
  280. * Returns the block length (in bits)
  281. *
  282. * @access public
  283. * @return int
  284. */
  285. public function getBlockLength()
  286. {
  287. return $this->blockSize;
  288. }
  289. /**
  290. * Returns the block length (in bytes)
  291. *
  292. * @access public
  293. * @return int
  294. */
  295. public function getBlockLengthInBytes()
  296. {
  297. return $this->blockSize >> 3;
  298. }
  299. /**
  300. * Pure-PHP implementation of SHA512
  301. *
  302. * @access private
  303. * @param string $m
  304. */
  305. private static function _sha512($m, $hash)
  306. {
  307. static $k;
  308. if (!isset($k)) {
  309. // Initialize table of round constants
  310. // (first 64 bits of the fractional parts of the cube roots of the first 80 primes 2..409)
  311. $k = array(
  312. '428a2f98d728ae22', '7137449123ef65cd', 'b5c0fbcfec4d3b2f', 'e9b5dba58189dbbc',
  313. '3956c25bf348b538', '59f111f1b605d019', '923f82a4af194f9b', 'ab1c5ed5da6d8118',
  314. 'd807aa98a3030242', '12835b0145706fbe', '243185be4ee4b28c', '550c7dc3d5ffb4e2',
  315. '72be5d74f27b896f', '80deb1fe3b1696b1', '9bdc06a725c71235', 'c19bf174cf692694',
  316. 'e49b69c19ef14ad2', 'efbe4786384f25e3', '0fc19dc68b8cd5b5', '240ca1cc77ac9c65',
  317. '2de92c6f592b0275', '4a7484aa6ea6e483', '5cb0a9dcbd41fbd4', '76f988da831153b5',
  318. '983e5152ee66dfab', 'a831c66d2db43210', 'b00327c898fb213f', 'bf597fc7beef0ee4',
  319. 'c6e00bf33da88fc2', 'd5a79147930aa725', '06ca6351e003826f', '142929670a0e6e70',
  320. '27b70a8546d22ffc', '2e1b21385c26c926', '4d2c6dfc5ac42aed', '53380d139d95b3df',
  321. '650a73548baf63de', '766a0abb3c77b2a8', '81c2c92e47edaee6', '92722c851482353b',
  322. 'a2bfe8a14cf10364', 'a81a664bbc423001', 'c24b8b70d0f89791', 'c76c51a30654be30',
  323. 'd192e819d6ef5218', 'd69906245565a910', 'f40e35855771202a', '106aa07032bbd1b8',
  324. '19a4c116b8d2d0c8', '1e376c085141ab53', '2748774cdf8eeb99', '34b0bcb5e19b48a8',
  325. '391c0cb3c5c95a63', '4ed8aa4ae3418acb', '5b9cca4f7763e373', '682e6ff3d6b2b8a3',
  326. '748f82ee5defb2fc', '78a5636f43172f60', '84c87814a1f0ab72', '8cc702081a6439ec',
  327. '90befffa23631e28', 'a4506cebde82bde9', 'bef9a3f7b2c67915', 'c67178f2e372532b',
  328. 'ca273eceea26619c', 'd186b8c721c0c207', 'eada7dd6cde0eb1e', 'f57d4f7fee6ed178',
  329. '06f067aa72176fba', '0a637dc5a2c898a6', '113f9804bef90dae', '1b710b35131c471b',
  330. '28db77f523047d84', '32caab7b40c72493', '3c9ebe0a15c9bebc', '431d67c49c100d4c',
  331. '4cc5d4becb3e42b6', '597f299cfc657e2a', '5fcb6fab3ad6faec', '6c44198c4a475817'
  332. );
  333. for ($i = 0; $i < 80; $i++) {
  334. $k[$i] = new BigInteger($k[$i], 16);
  335. }
  336. }
  337. // Pre-processing
  338. $length = strlen($m);
  339. // to round to nearest 112 mod 128, we'll add 128 - (length + (128 - 112)) % 128
  340. $m.= str_repeat(chr(0), 128 - (($length + 16) & 0x7F));
  341. $m[$length] = chr(0x80);
  342. // we don't support hashing strings 512MB long
  343. $m.= pack('N4', 0, 0, 0, $length << 3);
  344. // Process the message in successive 1024-bit chunks
  345. $chunks = str_split($m, 128);
  346. foreach ($chunks as $chunk) {
  347. $w = array();
  348. for ($i = 0; $i < 16; $i++) {
  349. $temp = new BigInteger(Strings::shift($chunk, 8), 256);
  350. $temp->setPrecision(64);
  351. $w[] = $temp;
  352. }
  353. // Extend the sixteen 32-bit words into eighty 32-bit words
  354. for ($i = 16; $i < 80; $i++) {
  355. $temp = array(
  356. $w[$i - 15]->bitwise_rightRotate(1),
  357. $w[$i - 15]->bitwise_rightRotate(8),
  358. $w[$i - 15]->bitwise_rightShift(7)
  359. );
  360. $s0 = $temp[0]->bitwise_xor($temp[1]);
  361. $s0 = $s0->bitwise_xor($temp[2]);
  362. $temp = array(
  363. $w[$i - 2]->bitwise_rightRotate(19),
  364. $w[$i - 2]->bitwise_rightRotate(61),
  365. $w[$i - 2]->bitwise_rightShift(6)
  366. );
  367. $s1 = $temp[0]->bitwise_xor($temp[1]);
  368. $s1 = $s1->bitwise_xor($temp[2]);
  369. $w[$i] = clone $w[$i - 16];
  370. $w[$i] = $w[$i]->add($s0);
  371. $w[$i] = $w[$i]->add($w[$i - 7]);
  372. $w[$i] = $w[$i]->add($s1);
  373. }
  374. // Initialize hash value for this chunk
  375. $a = clone $hash[0];
  376. $b = clone $hash[1];
  377. $c = clone $hash[2];
  378. $d = clone $hash[3];
  379. $e = clone $hash[4];
  380. $f = clone $hash[5];
  381. $g = clone $hash[6];
  382. $h = clone $hash[7];
  383. // Main loop
  384. for ($i = 0; $i < 80; $i++) {
  385. $temp = array(
  386. $a->bitwise_rightRotate(28),
  387. $a->bitwise_rightRotate(34),
  388. $a->bitwise_rightRotate(39)
  389. );
  390. $s0 = $temp[0]->bitwise_xor($temp[1]);
  391. $s0 = $s0->bitwise_xor($temp[2]);
  392. $temp = array(
  393. $a->bitwise_and($b),
  394. $a->bitwise_and($c),
  395. $b->bitwise_and($c)
  396. );
  397. $maj = $temp[0]->bitwise_xor($temp[1]);
  398. $maj = $maj->bitwise_xor($temp[2]);
  399. $t2 = $s0->add($maj);
  400. $temp = array(
  401. $e->bitwise_rightRotate(14),
  402. $e->bitwise_rightRotate(18),
  403. $e->bitwise_rightRotate(41)
  404. );
  405. $s1 = $temp[0]->bitwise_xor($temp[1]);
  406. $s1 = $s1->bitwise_xor($temp[2]);
  407. $temp = array(
  408. $e->bitwise_and($f),
  409. $g->bitwise_and($e->bitwise_not())
  410. );
  411. $ch = $temp[0]->bitwise_xor($temp[1]);
  412. $t1 = $h->add($s1);
  413. $t1 = $t1->add($ch);
  414. $t1 = $t1->add($k[$i]);
  415. $t1 = $t1->add($w[$i]);
  416. $h = clone $g;
  417. $g = clone $f;
  418. $f = clone $e;
  419. $e = $d->add($t1);
  420. $d = clone $c;
  421. $c = clone $b;
  422. $b = clone $a;
  423. $a = $t1->add($t2);
  424. }
  425. // Add this chunk's hash to result so far
  426. $hash = array(
  427. $hash[0]->add($a),
  428. $hash[1]->add($b),
  429. $hash[2]->add($c),
  430. $hash[3]->add($d),
  431. $hash[4]->add($e),
  432. $hash[5]->add($f),
  433. $hash[6]->add($g),
  434. $hash[7]->add($h)
  435. );
  436. }
  437. // Produce the final hash value (big-endian)
  438. // (\phpseclib\Crypt\Hash::hash() trims the output for hashes but not for HMACs. as such, we trim the output here)
  439. $temp = $hash[0]->toBytes() . $hash[1]->toBytes() . $hash[2]->toBytes() . $hash[3]->toBytes() .
  440. $hash[4]->toBytes() . $hash[5]->toBytes() . $hash[6]->toBytes() . $hash[7]->toBytes();
  441. return $temp;
  442. }
  443. }