nanoSha2.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. <?php
  2. /*
  3. * Transparent SHA-256 Implementation for PHP 4 and PHP 5
  4. *
  5. * Author: Perry McGee (pmcgee@nanolink.ca)
  6. * Website: http://www.nanolink.ca/pub/sha256
  7. *
  8. * Copyright (C) 2006,2007,2008,2009 Nanolink Solutions
  9. *
  10. * Created: Feb 11, 2006
  11. *
  12. * This library is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU Lesser General Public
  14. * License as published by the Free Software Foundation; either
  15. * version 2.1 of the License, or (at your option) any later version.
  16. *
  17. * This library is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. * Lesser General Public License for more details.
  21. * You should have received a copy of the GNU Lesser General Public
  22. * License along with this library; if not, write to the Free Software
  23. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24. * or see <http://www.gnu.org/licenses/>.
  25. *
  26. * Include:
  27. *
  28. * require_once("[path/]sha256.inc.php");
  29. *
  30. * Usage Options:
  31. *
  32. * 1) $shaStr = hash('sha256', $string_to_hash);
  33. *
  34. * 2) $shaStr = sha256($string_to_hash[, bool ignore_php5_hash = false]);
  35. *
  36. * 3) $obj = new nanoSha2([bool $upper_case_output = false]);
  37. * $shaStr = $obj->hash($string_to_hash[, bool $ignore_php5_hash = false]);
  38. *
  39. * Reference: http://csrc.nist.gov/groups/ST/toolkit/secure_hashing.html
  40. *
  41. * 2007-12-13: Cleaned up for initial public release
  42. * 2008-05-10: Moved all helper functions into a class. API access unchanged.
  43. * 2009-06-23: Created abstraction of hash() routine
  44. * 2009-07-23: Added detection of 32 vs 64bit platform, and patches.
  45. * Ability to define "_NANO_SHA2_UPPER" to yeild upper case hashes.
  46. * 2009-08-01: Added ability to attempt to use mhash() prior to running pure
  47. * php code.
  48. *
  49. * NOTE: Some sporadic versions of PHP do not handle integer overflows the
  50. * same as the majority of builds. If you get hash results of:
  51. * 7fffffff7fffffff7fffffff7fffffff7fffffff7fffffff7fffffff7fffffff
  52. *
  53. * If you do not have permissions to change PHP versions (if you did
  54. * you'd probably upgrade to PHP 5 anyway) it is advised you install a
  55. * module that will allow you to use their hashing routines, examples are:
  56. * - mhash module : http://ca3.php.net/mhash
  57. * - Suhosin : http://www.hardened-php.net/suhosin/
  58. *
  59. * If you install the Suhosin module, this script will transparently
  60. * use their routine and define the PHP routine as _nano_sha256().
  61. *
  62. * If the mhash module is present, and $ignore_php5_hash = false the
  63. * script will attempt to use the output from mhash prior to running
  64. * the PHP code.
  65. */
  66. class nanoSha2
  67. {
  68. // php 4 - 5 compatable class properties
  69. var $toUpper;
  70. var $platform;
  71. // Php 4 - 6 compatable constructor
  72. function nanoSha2($toUpper = false) {
  73. // Determine if the caller wants upper case or not.
  74. $this->toUpper = is_bool($toUpper)
  75. ? $toUpper
  76. : ((defined('_NANO_SHA2_UPPER')) ? true : false);
  77. // Deteremine if the system is 32 or 64 bit.
  78. $tmpInt = (int)4294967295;
  79. $this->platform = ($tmpInt > 0) ? 64 : 32;
  80. }
  81. // Do the SHA-256 Padding routine (make input a multiple of 512 bits)
  82. function char_pad($str)
  83. {
  84. $tmpStr = $str;
  85. $l = strlen($tmpStr)*8; // # of bits from input string
  86. $tmpStr .= "\x80"; // append the "1" bit followed by 7 0's
  87. $k = (512 - (($l + 8 + 64) % 512)) / 8; // # of 0 bytes to append
  88. $k += 4; // PHP Strings will never exceed (2^31)-1, 1st 32bits of
  89. // the 64-bit value representing $l can be all 0's
  90. for ($x = 0; $x < $k; $x++) {
  91. $tmpStr .= "\0";
  92. }
  93. // append the 32-bits representing # of bits from input string ($l)
  94. $tmpStr .= chr((($l>>24) & 0xFF));
  95. $tmpStr .= chr((($l>>16) & 0xFF));
  96. $tmpStr .= chr((($l>>8) & 0xFF));
  97. $tmpStr .= chr(($l & 0xFF));
  98. return $tmpStr;
  99. }
  100. // Here are the bitwise and functions as defined in FIPS180-2 Standard
  101. function addmod2n($x, $y, $n = 4294967296) // Z = (X + Y) mod 2^32
  102. {
  103. $mask = 0x80000000;
  104. if ($x < 0) {
  105. $x &= 0x7FFFFFFF;
  106. $x = (float)$x + $mask;
  107. }
  108. if ($y < 0) {
  109. $y &= 0x7FFFFFFF;
  110. $y = (float)$y + $mask;
  111. }
  112. $r = $x + $y;
  113. if ($r >= $n) {
  114. while ($r >= $n) {
  115. $r -= $n;
  116. }
  117. }
  118. return (int)$r;
  119. }
  120. // Logical bitwise right shift (PHP default is arithmetic shift)
  121. function SHR($x, $n) // x >> n
  122. {
  123. if ($n >= 32) { // impose some limits to keep it 32-bit
  124. return (int)0;
  125. }
  126. if ($n <= 0) {
  127. return (int)$x;
  128. }
  129. $mask = 0x40000000;
  130. if ($x < 0) {
  131. $x &= 0x7FFFFFFF;
  132. $mask = $mask >> ($n-1);
  133. return ($x >> $n) | $mask;
  134. }
  135. return (int)$x >> (int)$n;
  136. }
  137. function ROTR($x, $n) { return (int)(($this->SHR($x, $n) | ($x << (32-$n)) & 0xFFFFFFFF)); }
  138. function Ch($x, $y, $z) { return ($x & $y) ^ ((~$x) & $z); }
  139. function Maj($x, $y, $z) { return ($x & $y) ^ ($x & $z) ^ ($y & $z); }
  140. function Sigma0($x) { return (int) ($this->ROTR($x, 2)^$this->ROTR($x, 13)^$this->ROTR($x, 22)); }
  141. function Sigma1($x) { return (int) ($this->ROTR($x, 6)^$this->ROTR($x, 11)^$this->ROTR($x, 25)); }
  142. function sigma_0($x) { return (int) ($this->ROTR($x, 7)^$this->ROTR($x, 18)^$this->SHR($x, 3)); }
  143. function sigma_1($x) { return (int) ($this->ROTR($x, 17)^$this->ROTR($x, 19)^$this->SHR($x, 10)); }
  144. /*
  145. * Custom functions to provide PHP support
  146. */
  147. // split a byte-string into integer array values
  148. function int_split($input)
  149. {
  150. $l = strlen($input);
  151. if ($l <= 0) {
  152. return (int)0;
  153. }
  154. if (($l % 4) != 0) { // invalid input
  155. return false;
  156. }
  157. for ($i = 0; $i < $l; $i += 4)
  158. {
  159. $int_build = (ord($input[$i]) << 24);
  160. $int_build += (ord($input[$i+1]) << 16);
  161. $int_build += (ord($input[$i+2]) << 8);
  162. $int_build += (ord($input[$i+3]));
  163. $result[] = $int_build;
  164. }
  165. return $result;
  166. }
  167. /**
  168. * Process and return the hash.
  169. *
  170. * @param $str Input string to hash
  171. * @param $ig_func Option param to ignore checking for php > 5.1.2
  172. * @return string Hexadecimal representation of the message digest
  173. */
  174. function hash($str, $ig_func = false)
  175. {
  176. unset($binStr); // binary representation of input string
  177. unset($hexStr); // 256-bit message digest in readable hex format
  178. // check for php's internal sha256 function, ignore if ig_func==true
  179. if ($ig_func == false) {
  180. if (version_compare(PHP_VERSION,'5.1.2','>=')) {
  181. return hash("sha256", $str, false);
  182. } else if (function_exists('mhash') && defined('MHASH_SHA256')) {
  183. return base64_encode(bin2hex(mhash(MHASH_SHA256, $str)));
  184. }
  185. }
  186. /*
  187. * SHA-256 Constants
  188. * Sequence of sixty-four constant 32-bit words representing the
  189. * first thirty-two bits of the fractional parts of the cube roots
  190. * of the first sixtyfour prime numbers.
  191. */
  192. $K = array((int)0x428a2f98, (int)0x71374491, (int)0xb5c0fbcf,
  193. (int)0xe9b5dba5, (int)0x3956c25b, (int)0x59f111f1,
  194. (int)0x923f82a4, (int)0xab1c5ed5, (int)0xd807aa98,
  195. (int)0x12835b01, (int)0x243185be, (int)0x550c7dc3,
  196. (int)0x72be5d74, (int)0x80deb1fe, (int)0x9bdc06a7,
  197. (int)0xc19bf174, (int)0xe49b69c1, (int)0xefbe4786,
  198. (int)0x0fc19dc6, (int)0x240ca1cc, (int)0x2de92c6f,
  199. (int)0x4a7484aa, (int)0x5cb0a9dc, (int)0x76f988da,
  200. (int)0x983e5152, (int)0xa831c66d, (int)0xb00327c8,
  201. (int)0xbf597fc7, (int)0xc6e00bf3, (int)0xd5a79147,
  202. (int)0x06ca6351, (int)0x14292967, (int)0x27b70a85,
  203. (int)0x2e1b2138, (int)0x4d2c6dfc, (int)0x53380d13,
  204. (int)0x650a7354, (int)0x766a0abb, (int)0x81c2c92e,
  205. (int)0x92722c85, (int)0xa2bfe8a1, (int)0xa81a664b,
  206. (int)0xc24b8b70, (int)0xc76c51a3, (int)0xd192e819,
  207. (int)0xd6990624, (int)0xf40e3585, (int)0x106aa070,
  208. (int)0x19a4c116, (int)0x1e376c08, (int)0x2748774c,
  209. (int)0x34b0bcb5, (int)0x391c0cb3, (int)0x4ed8aa4a,
  210. (int)0x5b9cca4f, (int)0x682e6ff3, (int)0x748f82ee,
  211. (int)0x78a5636f, (int)0x84c87814, (int)0x8cc70208,
  212. (int)0x90befffa, (int)0xa4506ceb, (int)0xbef9a3f7,
  213. (int)0xc67178f2);
  214. // Pre-processing: Padding the string
  215. $binStr = $this->char_pad($str);
  216. // Parsing the Padded Message (Break into N 512-bit blocks)
  217. $M = str_split($binStr, 64);
  218. // Set the initial hash values
  219. $h[0] = (int)0x6a09e667;
  220. $h[1] = (int)0xbb67ae85;
  221. $h[2] = (int)0x3c6ef372;
  222. $h[3] = (int)0xa54ff53a;
  223. $h[4] = (int)0x510e527f;
  224. $h[5] = (int)0x9b05688c;
  225. $h[6] = (int)0x1f83d9ab;
  226. $h[7] = (int)0x5be0cd19;
  227. // loop through message blocks and compute hash. ( For i=1 to N : )
  228. $N = count($M);
  229. for ($i = 0; $i < $N; $i++)
  230. {
  231. // Break input block into 16 32bit words (message schedule prep)
  232. $MI = $this->int_split($M[$i]);
  233. // Initialize working variables
  234. $_a = (int)$h[0];
  235. $_b = (int)$h[1];
  236. $_c = (int)$h[2];
  237. $_d = (int)$h[3];
  238. $_e = (int)$h[4];
  239. $_f = (int)$h[5];
  240. $_g = (int)$h[6];
  241. $_h = (int)$h[7];
  242. unset($_s0);
  243. unset($_s1);
  244. unset($_T1);
  245. unset($_T2);
  246. $W = array();
  247. // Compute the hash and update
  248. for ($t = 0; $t < 16; $t++)
  249. {
  250. // Prepare the first 16 message schedule values as we loop
  251. $W[$t] = $MI[$t];
  252. // Compute hash
  253. $_T1 = $this->addmod2n($this->addmod2n($this->addmod2n($this->addmod2n($_h, $this->Sigma1($_e)), $this->Ch($_e, $_f, $_g)), $K[$t]), $W[$t]);
  254. $_T2 = $this->addmod2n($this->Sigma0($_a), $this->Maj($_a, $_b, $_c));
  255. // Update working variables
  256. $_h = $_g; $_g = $_f; $_f = $_e; $_e = $this->addmod2n($_d, $_T1);
  257. $_d = $_c; $_c = $_b; $_b = $_a; $_a = $this->addmod2n($_T1, $_T2);
  258. }
  259. for (; $t < 64; $t++)
  260. {
  261. // Continue building the message schedule as we loop
  262. $_s0 = $W[($t+1)&0x0F];
  263. $_s0 = $this->sigma_0($_s0);
  264. $_s1 = $W[($t+14)&0x0F];
  265. $_s1 = $this->sigma_1($_s1);
  266. $W[$t&0xF] = $this->addmod2n($this->addmod2n($this->addmod2n($W[$t&0xF], $_s0), $_s1), $W[($t+9)&0x0F]);
  267. // Compute hash
  268. $_T1 = $this->addmod2n($this->addmod2n($this->addmod2n($this->addmod2n($_h, $this->Sigma1($_e)), $this->Ch($_e, $_f, $_g)), $K[$t]), $W[$t&0xF]);
  269. $_T2 = $this->addmod2n($this->Sigma0($_a), $this->Maj($_a, $_b, $_c));
  270. // Update working variables
  271. $_h = $_g; $_g = $_f; $_f = $_e; $_e = $this->addmod2n($_d, $_T1);
  272. $_d = $_c; $_c = $_b; $_b = $_a; $_a = $this->addmod2n($_T1, $_T2);
  273. }
  274. $h[0] = $this->addmod2n($h[0], $_a);
  275. $h[1] = $this->addmod2n($h[1], $_b);
  276. $h[2] = $this->addmod2n($h[2], $_c);
  277. $h[3] = $this->addmod2n($h[3], $_d);
  278. $h[4] = $this->addmod2n($h[4], $_e);
  279. $h[5] = $this->addmod2n($h[5], $_f);
  280. $h[6] = $this->addmod2n($h[6], $_g);
  281. $h[7] = $this->addmod2n($h[7], $_h);
  282. }
  283. // Convert the 32-bit words into human readable hexadecimal format.
  284. $hexStr = sprintf("%08x%08x%08x%08x%08x%08x%08x%08x", $h[0], $h[1], $h[2], $h[3], $h[4], $h[5], $h[6], $h[7]);
  285. return ($this->toUpper) ? strtoupper($hexStr) : $hexStr;
  286. }
  287. }