PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/spip/ecrire/auth/sha256.inc.php

https://github.com/eyeswebcrea/espace-couture-sittler.fr
PHP | 446 lines | 272 code | 50 blank | 124 comment | 50 complexity | f5144101bcdfac5d2cf45a0788d76f8f MD5 | raw file
Possible License(s): LGPL-2.1, GPL-3.0
  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. * 2010-06-10: Added support for 16bytes char and utf8 in string
  50. *
  51. * NOTE: Some sporadic versions of PHP do not handle integer overflows the
  52. * same as the majority of builds. If you get hash results of:
  53. * 7fffffff7fffffff7fffffff7fffffff7fffffff7fffffff7fffffff7fffffff
  54. *
  55. * If you do not have permissions to change PHP versions (if you did
  56. * you'd probably upgrade to PHP 5 anyway) it is advised you install a
  57. * module that will allow you to use their hashing routines, examples are:
  58. * - mhash module : http://ca3.php.net/mhash
  59. * - Suhosin : http://www.hardened-php.net/suhosin/
  60. *
  61. * If you install the Suhosin module, this script will transparently
  62. * use their routine and define the PHP routine as _nano_sha256().
  63. *
  64. * If the mhash module is present, and $ignore_php5_hash = false the
  65. * script will attempt to use the output from mhash prior to running
  66. * the PHP code.
  67. */
  68. if (!class_exists('nanoSha2'))
  69. {
  70. class nanoSha2
  71. {
  72. // php 4 - 5 compatable class properties
  73. var $toUpper;
  74. var $platform;
  75. var $bytesString = 16;
  76. // Php 4 - 6 compatable constructor
  77. function nanoSha2($toUpper = false) {
  78. // Determine if the caller wants upper case or not.
  79. $this->toUpper = is_bool($toUpper)
  80. ? $toUpper
  81. : ((defined('_NANO_SHA2_UPPER')) ? true : false);
  82. // Deteremine if the system is 32 or 64 bit.
  83. $tmpInt = (int)4294967295;
  84. $this->platform = ($tmpInt > 0) ? 64 : 32;
  85. }
  86. // Here are the bitwise and functions as defined in FIPS180-2 Standard
  87. function addmod2n($x, $y, $n = 4294967296) // Z = (X + Y) mod 2^32
  88. {
  89. $mask = 0x80000000;
  90. if ($x < 0) {
  91. $x &= 0x7FFFFFFF;
  92. $x = (float)$x + $mask;
  93. }
  94. if ($y < 0) {
  95. $y &= 0x7FFFFFFF;
  96. $y = (float)$y + $mask;
  97. }
  98. $r = $x + $y;
  99. if ($r >= $n) {
  100. while ($r >= $n) {
  101. $r -= $n;
  102. }
  103. }
  104. return (int)$r;
  105. }
  106. // Logical bitwise right shift (PHP default is arithmetic shift)
  107. function SHR($x, $n) // x >> n
  108. {
  109. if ($n >= 32) { // impose some limits to keep it 32-bit
  110. return (int)0;
  111. }
  112. if ($n <= 0) {
  113. return (int)$x;
  114. }
  115. $mask = 0x40000000;
  116. if ($x < 0) {
  117. $x &= 0x7FFFFFFF;
  118. $mask = $mask >> ($n-1);
  119. return ($x >> $n) | $mask;
  120. }
  121. return (int)$x >> (int)$n;
  122. }
  123. function ROTR($x, $n) { return (int)(($this->SHR($x, $n) | ($x << (32-$n)) & 0xFFFFFFFF)); }
  124. function Ch($x, $y, $z) { return ($x & $y) ^ ((~$x) & $z); }
  125. function Maj($x, $y, $z) { return ($x & $y) ^ ($x & $z) ^ ($y & $z); }
  126. function Sigma0($x) { return (int) ($this->ROTR($x, 2)^$this->ROTR($x, 13)^$this->ROTR($x, 22)); }
  127. function Sigma1($x) { return (int) ($this->ROTR($x, 6)^$this->ROTR($x, 11)^$this->ROTR($x, 25)); }
  128. function sigma_0($x) { return (int) ($this->ROTR($x, 7)^$this->ROTR($x, 18)^$this->SHR($x, 3)); }
  129. function sigma_1($x) { return (int) ($this->ROTR($x, 17)^$this->ROTR($x, 19)^$this->SHR($x, 10)); }
  130. function string2ordUTF8($s,&$byteSize){
  131. $chars = array();
  132. // par defaut sur 8bits
  133. $byteSize = 8;
  134. $i = 0;
  135. while ($i<strlen($s)){
  136. $chars[] = $this->ordUTF8($s, $i, $bytes);
  137. $i+=$bytes;
  138. // mais si un char necessite 16bits, on passe tout sur 16
  139. // sinon on ne concorde pas avec le lecture de la chaine en js
  140. // et le sha256 js
  141. if ($bytes>1) $byteSize = 16;
  142. }
  143. return $chars;
  144. }
  145. function ordUTF8($c, $index = 0, &$bytes)
  146. {
  147. $len = strlen($c);
  148. $bytes = 0;
  149. if ($index >= $len)
  150. return false;
  151. $h = ord($c{$index});
  152. if ($h <= 0x7F) {
  153. $bytes = 1;
  154. return $h;
  155. }
  156. else if ($h < 0xC2){
  157. // pas utf mais renvoyer quand meme ce qu'on a
  158. $bytes = 1;
  159. return $h;
  160. }
  161. else if ($h <= 0xDF && $index < $len - 1) {
  162. $bytes = 2;
  163. return ($h & 0x1F) << 6 | (ord($c{$index + 1}) & 0x3F);
  164. }
  165. else if ($h <= 0xEF && $index < $len - 2) {
  166. $bytes = 3;
  167. return ($h & 0x0F) << 12 | (ord($c{$index + 1}) & 0x3F) << 6
  168. | (ord($c{$index + 2}) & 0x3F);
  169. }
  170. else if ($h <= 0xF4 && $index < $len - 3) {
  171. $bytes = 4;
  172. return ($h & 0x0F) << 18 | (ord($c{$index + 1}) & 0x3F) << 12
  173. | (ord($c{$index + 2}) & 0x3F) << 6
  174. | (ord($c{$index + 3}) & 0x3F);
  175. }
  176. else {
  177. // pas utf mais renvoyer quand meme ce qu'on a
  178. $bytes = 1;
  179. return $h;
  180. }
  181. }
  182. function string2binint ($str,$npad=512) {
  183. $bin = array();
  184. $ords = $this->string2ordUTF8($str,$this->bytesString);
  185. $npad = $npad/$this->bytesString;
  186. $length = count($ords);
  187. $ords[] = 0x80; // append the "1" bit followed by 7 0's
  188. $ords = array_pad($ords,ceil(($length+32/$this->bytesString)/$npad)*$npad-32/$this->bytesString,0);
  189. $mask = (1 << $this->bytesString) - 1;
  190. for($i = 0; $i < count($ords) * $this->bytesString; $i += $this->bytesString)
  191. $bin[$i>>5] |= ($ords[$i / $this->bytesString] & $mask) << (24 - $i%32);
  192. $bin[] = $length*$this->bytesString;
  193. return $bin;
  194. }
  195. function array_split($a, $n) {
  196. $split = array();
  197. while (count($a)>$n) {
  198. $s = array();
  199. for($i = 0;$i<$n;$i++)
  200. $s[] = array_shift($a);
  201. $split[] = $s;
  202. }
  203. if (count($a)){
  204. $a = array_pad($a,$n,0);
  205. $split[] = $a;
  206. }
  207. return $split;
  208. }
  209. /**
  210. * Process and return the hash.
  211. *
  212. * @param $str Input string to hash
  213. * @param $ig_func Option param to ignore checking for php > 5.1.2
  214. * @return string Hexadecimal representation of the message digest
  215. */
  216. function hash($str, $ig_func = true)
  217. {
  218. unset($binStr); // binary representation of input string
  219. unset($hexStr); // 256-bit message digest in readable hex format
  220. // check for php's internal sha256 function, ignore if ig_func==true
  221. if ($ig_func == false) {
  222. if (version_compare(PHP_VERSION,'5.1.2','>=') AND !defined('_NO_HASH_DEFINED')) {
  223. return hash("sha256", $str, false);
  224. } else if (function_exists('mhash') && defined('MHASH_SHA256')) {
  225. return base64_encode(bin2hex(mhash(MHASH_SHA256, $str)));
  226. }
  227. }
  228. /*
  229. * SHA-256 Constants
  230. * Sequence of sixty-four constant 32-bit words representing the
  231. * first thirty-two bits of the fractional parts of the cube roots
  232. * of the first sixtyfour prime numbers.
  233. */
  234. $K = array((int)0x428a2f98, (int)0x71374491, (int)0xb5c0fbcf,
  235. (int)0xe9b5dba5, (int)0x3956c25b, (int)0x59f111f1,
  236. (int)0x923f82a4, (int)0xab1c5ed5, (int)0xd807aa98,
  237. (int)0x12835b01, (int)0x243185be, (int)0x550c7dc3,
  238. (int)0x72be5d74, (int)0x80deb1fe, (int)0x9bdc06a7,
  239. (int)0xc19bf174, (int)0xe49b69c1, (int)0xefbe4786,
  240. (int)0x0fc19dc6, (int)0x240ca1cc, (int)0x2de92c6f,
  241. (int)0x4a7484aa, (int)0x5cb0a9dc, (int)0x76f988da,
  242. (int)0x983e5152, (int)0xa831c66d, (int)0xb00327c8,
  243. (int)0xbf597fc7, (int)0xc6e00bf3, (int)0xd5a79147,
  244. (int)0x06ca6351, (int)0x14292967, (int)0x27b70a85,
  245. (int)0x2e1b2138, (int)0x4d2c6dfc, (int)0x53380d13,
  246. (int)0x650a7354, (int)0x766a0abb, (int)0x81c2c92e,
  247. (int)0x92722c85, (int)0xa2bfe8a1, (int)0xa81a664b,
  248. (int)0xc24b8b70, (int)0xc76c51a3, (int)0xd192e819,
  249. (int)0xd6990624, (int)0xf40e3585, (int)0x106aa070,
  250. (int)0x19a4c116, (int)0x1e376c08, (int)0x2748774c,
  251. (int)0x34b0bcb5, (int)0x391c0cb3, (int)0x4ed8aa4a,
  252. (int)0x5b9cca4f, (int)0x682e6ff3, (int)0x748f82ee,
  253. (int)0x78a5636f, (int)0x84c87814, (int)0x8cc70208,
  254. (int)0x90befffa, (int)0xa4506ceb, (int)0xbef9a3f7,
  255. (int)0xc67178f2);
  256. // Pre-processing: Padding the string
  257. $binStr = $this->string2binint($str,512);
  258. // Parsing the Padded Message (Break into N 512-bit blocks)
  259. $M = $this->array_split($binStr, 16);
  260. // Set the initial hash values
  261. $h[0] = (int)0x6a09e667;
  262. $h[1] = (int)0xbb67ae85;
  263. $h[2] = (int)0x3c6ef372;
  264. $h[3] = (int)0xa54ff53a;
  265. $h[4] = (int)0x510e527f;
  266. $h[5] = (int)0x9b05688c;
  267. $h[6] = (int)0x1f83d9ab;
  268. $h[7] = (int)0x5be0cd19;
  269. // loop through message blocks and compute hash. ( For i=1 to N : )
  270. $N = count($M);
  271. for ($i = 0; $i < $N; $i++)
  272. {
  273. // Break input block into 16 32bit words (message schedule prep)
  274. $MI = $M[$i];
  275. // Initialize working variables
  276. $_a = (int)$h[0];
  277. $_b = (int)$h[1];
  278. $_c = (int)$h[2];
  279. $_d = (int)$h[3];
  280. $_e = (int)$h[4];
  281. $_f = (int)$h[5];
  282. $_g = (int)$h[6];
  283. $_h = (int)$h[7];
  284. unset($_s0);
  285. unset($_s1);
  286. unset($_T1);
  287. unset($_T2);
  288. $W = array();
  289. // Compute the hash and update
  290. for ($t = 0; $t < 16; $t++)
  291. {
  292. // Prepare the first 16 message schedule values as we loop
  293. $W[$t] = $MI[$t];
  294. // Compute hash
  295. $_T1 = $this->addmod2n($this->addmod2n($this->addmod2n($this->addmod2n($_h, $this->Sigma1($_e)), $this->Ch($_e, $_f, $_g)), $K[$t]), $W[$t]);
  296. $_T2 = $this->addmod2n($this->Sigma0($_a), $this->Maj($_a, $_b, $_c));
  297. // Update working variables
  298. $_h = $_g; $_g = $_f; $_f = $_e; $_e = $this->addmod2n($_d, $_T1);
  299. $_d = $_c; $_c = $_b; $_b = $_a; $_a = $this->addmod2n($_T1, $_T2);
  300. }
  301. for (; $t < 64; $t++)
  302. {
  303. // Continue building the message schedule as we loop
  304. $_s0 = $W[($t+1)&0x0F];
  305. $_s0 = $this->sigma_0($_s0);
  306. $_s1 = $W[($t+14)&0x0F];
  307. $_s1 = $this->sigma_1($_s1);
  308. $W[$t&0xF] = $this->addmod2n($this->addmod2n($this->addmod2n($W[$t&0xF], $_s0), $_s1), $W[($t+9)&0x0F]);
  309. // Compute hash
  310. $_T1 = $this->addmod2n($this->addmod2n($this->addmod2n($this->addmod2n($_h, $this->Sigma1($_e)), $this->Ch($_e, $_f, $_g)), $K[$t]), $W[$t&0xF]);
  311. $_T2 = $this->addmod2n($this->Sigma0($_a), $this->Maj($_a, $_b, $_c));
  312. // Update working variables
  313. $_h = $_g; $_g = $_f; $_f = $_e; $_e = $this->addmod2n($_d, $_T1);
  314. $_d = $_c; $_c = $_b; $_b = $_a; $_a = $this->addmod2n($_T1, $_T2);
  315. }
  316. $h[0] = $this->addmod2n($h[0], $_a);
  317. $h[1] = $this->addmod2n($h[1], $_b);
  318. $h[2] = $this->addmod2n($h[2], $_c);
  319. $h[3] = $this->addmod2n($h[3], $_d);
  320. $h[4] = $this->addmod2n($h[4], $_e);
  321. $h[5] = $this->addmod2n($h[5], $_f);
  322. $h[6] = $this->addmod2n($h[6], $_g);
  323. $h[7] = $this->addmod2n($h[7], $_h);
  324. }
  325. // Convert the 32-bit words into human readable hexadecimal format.
  326. $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]);
  327. return ($this->toUpper) ? strtoupper($hexStr) : $hexStr;
  328. }
  329. }
  330. }
  331. if (!function_exists('str_split'))
  332. {
  333. /**
  334. * Splits a string into an array of strings with specified length.
  335. * Compatability with older verions of PHP
  336. */
  337. function str_split($string, $split_length = 1)
  338. {
  339. $sign = ($split_length < 0) ? -1 : 1;
  340. $strlen = strlen($string);
  341. $split_length = abs($split_length);
  342. if (($split_length == 0) || ($strlen == 0)) {
  343. $result = false;
  344. } elseif ($split_length >= $strlen) {
  345. $result[] = $string;
  346. } else {
  347. $length = $split_length;
  348. for ($i = 0; $i < $strlen; $i++)
  349. {
  350. $i = (($sign < 0) ? $i + $length : $i);
  351. $result[] = substr($string, $sign*$i, $length);
  352. $i--;
  353. $i = (($sign < 0) ? $i : $i + $length);
  354. $length = (($i + $split_length) > $strlen)
  355. ? ($strlen - ($i + 1))
  356. : $split_length;
  357. }
  358. }
  359. return $result;
  360. }
  361. }
  362. /**
  363. * Main routine called from an application using this include.
  364. *
  365. * General usage:
  366. * require_once('sha256.inc.php');
  367. * $hashstr = sha256('abc');
  368. *
  369. * Note:
  370. * PHP Strings are limitd to (2^31)-1, so it is not worth it to
  371. * check for input strings > 2^64 as the FIPS180-2 defines.
  372. */
  373. function _nano_sha256($str, $ig_func = true) {
  374. $obj = new nanoSha2((defined('_NANO_SHA2_UPPER')) ? true : false);
  375. return $obj->hash($str, $ig_func);
  376. }
  377. // 2009-07-23: Added check for function as the Suhosin plugin adds this routine.
  378. if (!function_exists('sha256')) {
  379. function sha256($str, $ig_func = true) { return _nano_sha256($str, $ig_func); }
  380. }
  381. // support to give php4 the hash() routine which abstracts this code.
  382. if (!function_exists('hash'))
  383. {
  384. define('_NO_HASH_DEFINED',true);
  385. function hash($algo, $data)
  386. {
  387. if (empty($algo) || !is_string($algo) || !is_string($data)) {
  388. return false;
  389. }
  390. if (function_exists($algo)) {
  391. return $algo($data);
  392. }
  393. }
  394. }
  395. ?>