3 * Transparent SHA-256 Implementation for PHP 4 and PHP 5
5 * Author: Perry McGee (pmcgee@nanolink.ca)
6 * Website: http://www.nanolink.ca/pub/sha256
8 * Copyright (C) 2006,2007,2008,2009 Nanolink Solutions
10 * Created: Feb 11, 2006
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.
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/>.
28 * require_once("[path/]sha256.inc.php");
32 * 1) $shaStr = hash('sha256', $string_to_hash);
34 * 2) $shaStr = sha256($string_to_hash[, bool ignore_php5_hash = false]);
36 * 3) $obj = new nanoSha2([bool $upper_case_output = false]);
37 * $shaStr = $obj->hash($string_to_hash[, bool $ignore_php5_hash = false]);
39 * Reference: http://csrc.nist.gov/groups/ST/toolkit/secure_hashing.html
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
49 * 2010-06-10: Added support for 16bytes char and utf8 in string
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
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/
61 * If you install the Suhosin module, this script will transparently
62 * use their routine and define the PHP routine as _nano_sha256().
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
68 * @package SPIP\Core\Authentification\Sha256
70 if (!class_exists('nanoSha2')) {
72 * Classe de calcul d'un SHA
75 // php 4 - 5 compatable class properties
76 /** Le résultat doit être passé en majuscule ?
86 /** bytes par caractères */
87 var $bytesString = 16;
92 * @param bool $toUpper
94 function __construct($toUpper = false) {
95 // Determine if the caller wants upper case or not.
96 $this->toUpper
= is_bool($toUpper)
98 : ((defined('_NANO_SHA2_UPPER')) ?
true : false);
100 // Deteremine if the system is 32 or 64 bit.
101 $tmpInt = (int)4294967295;
102 $this->platform
= ($tmpInt > 0) ?
64 : 32;
106 * Here are the bitwise and functions as defined in FIPS180-2 Standard
113 function addmod2n($x, $y, $n = 4294967296) // Z = (X + Y) mod 2^32
119 $x = (float)$x+
$mask;
124 $y = (float)$y+
$mask;
139 * Logical bitwise right shift (PHP default is arithmetic shift)
145 function SHR($x, $n) // x >> n
147 if ($n >= 32) { // impose some limits to keep it 32-bit
159 $mask = $mask >> ($n-1);
161 return ($x >> $n) |
$mask;
164 return (int)$x >> (int)$n;
173 function ROTR($x, $n) { return (int)(($this->SHR($x, $n) |
($x << (32-$n)) & 0xFFFFFFFF)); }
182 function Ch($x, $y, $z) { return ($x & $y) ^
((~
$x) & $z); }
191 function Maj($x, $y, $z) { return ($x & $y) ^
($x & $z) ^
($y & $z); }
198 function Sigma0($x) { return (int)($this->ROTR($x, 2) ^
$this->ROTR($x, 13) ^
$this->ROTR($x, 22)); }
205 function Sigma1($x) { return (int)($this->ROTR($x, 6) ^
$this->ROTR($x, 11) ^
$this->ROTR($x, 25)); }
212 function sigma_0($x) { return (int)($this->ROTR($x, 7) ^
$this->ROTR($x, 18) ^
$this->SHR($x, 3)); }
219 function sigma_1($x) { return (int)($this->ROTR($x, 17) ^
$this->ROTR($x, 19) ^
$this->SHR($x, 10)); }
221 /** String 2 ord UTF8
224 * @param int $byteSize
227 function string2ordUTF8($s, &$byteSize) {
229 // par defaut sur 8bits
232 while ($i < strlen($s)) {
233 $chars[] = $this->ordUTF8($s, $i, $bytes);
235 // mais si un char necessite 16bits, on passe tout sur 16
236 // sinon on ne concorde pas avec le lecture de la chaine en js
253 function ordUTF8($c, $index = 0, &$bytes) {
257 if ($index >= $len) {
261 $h = ord($c{$index});
269 // pas utf mais renvoyer quand meme ce qu'on a
274 if ($h <= 0xDF && $index < $len-1) {
277 return ($h & 0x1F) << 6 |
(ord($c{$index+
1}) & 0x3F);
279 if ($h <= 0xEF && $index < $len-2) {
282 return ($h & 0x0F) << 12 |
(ord($c{$index+
1}) & 0x3F) << 6
283 |
(ord($c{$index+
2}) & 0x3F);
285 if ($h <= 0xF4 && $index < $len-3) {
288 return ($h & 0x0F) << 18 |
(ord($c{$index+
1}) & 0x3F) << 12
289 |
(ord($c{$index+
2}) & 0x3F) << 6
290 |
(ord($c{$index+
3}) & 0x3F);
292 // pas utf mais renvoyer quand meme ce qu'on a
309 function string2binint($str, $npad = 512) {
311 $ords = $this->string2ordUTF8($str, $this->bytesString
);
312 $npad = $npad/$this->bytesString
;
313 $length = count($ords);
314 $ords[] = 0x80; // append the "1" bit followed by 7 0's
315 $pad = ceil(($length+
1+
32/$this->bytesString
)/$npad)*$npad-32/$this->bytesString
;
316 $ords = array_pad($ords, $pad, 0);
317 $mask = (1 << $this->bytesString
)-1;
318 for ($i = 0; $i < count($ords)*$this->bytesString
; $i +
= $this->bytesString
) {
319 if (!isset($bin[$i >> 5])) {
321 } // pour eviter des notices.
322 $bin[$i >> 5] |
= ($ords[$i/$this->bytesString
] & $mask) << (24-$i%32
);
324 $bin[] = $length*$this->bytesString
;
335 function array_split($a, $n) {
337 while (count($a) > $n) {
339 for ($i = 0; $i < $n; $i++
) {
340 $s[] = array_shift($a);
345 $a = array_pad($a, $n, 0);
353 * Process and return the hash.
355 * @param $str Input string to hash
356 * @param $ig_func Option param to ignore checking for php > 5.1.2
357 * @return string Hexadecimal representation of the message digest
359 function hash($str, $ig_func = true) {
360 unset($binStr); // binary representation of input string
361 unset($hexStr); // 256-bit message digest in readable hex format
363 // check for php's internal sha256 function, ignore if ig_func==true
364 if ($ig_func == false) {
365 if (version_compare(PHP_VERSION
, '5.1.2', '>=') AND !defined('_NO_HASH_DEFINED')) {
366 return hash("sha256", $str, false);
368 if (function_exists('mhash') && defined('MHASH_SHA256')) {
369 return base64_encode(bin2hex(mhash(MHASH_SHA256
, $str)));
376 * Sequence of sixty-four constant 32-bit words representing the
377 * first thirty-two bits of the fractional parts of the cube roots
378 * of the first sixtyfour prime numbers.
447 // Pre-processing: Padding the string
448 $binStr = $this->string2binint($str, 512);
450 // Parsing the Padded Message (Break into N 512-bit blocks)
451 $M = $this->array_split($binStr, 16);
453 // Set the initial hash values
454 $h[0] = (int)0x6a09e667;
455 $h[1] = (int)0xbb67ae85;
456 $h[2] = (int)0x3c6ef372;
457 $h[3] = (int)0xa54ff53a;
458 $h[4] = (int)0x510e527f;
459 $h[5] = (int)0x9b05688c;
460 $h[6] = (int)0x1f83d9ab;
461 $h[7] = (int)0x5be0cd19;
463 // loop through message blocks and compute hash. ( For i=1 to N : )
465 for ($i = 0; $i < $N; $i++
) {
466 // Break input block into 16 32bit words (message schedule prep)
469 // Initialize working variables
484 // Compute the hash and update
485 for ($t = 0; $t < 16; $t++
) {
486 // Prepare the first 16 message schedule values as we loop
490 $_T1 = $this->addmod2n($this->addmod2n($this->addmod2n($this->addmod2n($_h, $this->Sigma1($_e)),
491 $this->Ch($_e, $_f, $_g)), $K[$t]), $W[$t]);
492 $_T2 = $this->addmod2n($this->Sigma0($_a), $this->Maj($_a, $_b, $_c));
494 // Update working variables
498 $_e = $this->addmod2n($_d, $_T1);
502 $_a = $this->addmod2n($_T1, $_T2);
505 for (; $t < 64; $t++
) {
506 // Continue building the message schedule as we loop
507 $_s0 = $W[($t+
1) & 0x0F];
508 $_s0 = $this->sigma_0($_s0);
509 $_s1 = $W[($t+
14) & 0x0F];
510 $_s1 = $this->sigma_1($_s1);
512 $W[$t & 0xF] = $this->addmod2n($this->addmod2n($this->addmod2n($W[$t & 0xF], $_s0), $_s1), $W[($t+
9) & 0x0F]);
515 $_T1 = $this->addmod2n($this->addmod2n($this->addmod2n($this->addmod2n($_h, $this->Sigma1($_e)),
516 $this->Ch($_e, $_f, $_g)), $K[$t]), $W[$t & 0xF]);
517 $_T2 = $this->addmod2n($this->Sigma0($_a), $this->Maj($_a, $_b, $_c));
519 // Update working variables
523 $_e = $this->addmod2n($_d, $_T1);
527 $_a = $this->addmod2n($_T1, $_T2);
530 $h[0] = $this->addmod2n($h[0], $_a);
531 $h[1] = $this->addmod2n($h[1], $_b);
532 $h[2] = $this->addmod2n($h[2], $_c);
533 $h[3] = $this->addmod2n($h[3], $_d);
534 $h[4] = $this->addmod2n($h[4], $_e);
535 $h[5] = $this->addmod2n($h[5], $_f);
536 $h[6] = $this->addmod2n($h[6], $_g);
537 $h[7] = $this->addmod2n($h[7], $_h);
540 // Convert the 32-bit words into human readable hexadecimal format.
541 $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]);
543 return ($this->toUpper
) ?
strtoupper($hexStr) : $hexStr;
550 * Main routine called from an application using this include.
553 * require_once('sha256.inc.php');
554 * $hashstr = sha256('abc');
557 * PHP Strings are limitd to (2^31)-1, so it is not worth it to
558 * check for input strings > 2^64 as the FIPS180-2 defines.
560 * @param string $str Chaîne dont on veut calculer le SHA
561 * @param bool $ig_func
562 * @return string Le SHA de la chaîne
564 function _nano_sha256($str, $ig_func = true) {
565 $obj = new nanoSha2((defined('_NANO_SHA2_UPPER')) ?
true : false);
567 return $obj->hash($str, $ig_func);
570 // 2009-07-23: Added check for function as the Suhosin plugin adds this routine.
571 if (!function_exists('sha256')) {
575 * @param string $str Chaîne dont on veut calculer le SHA
576 * @param bool $ig_func
577 * @return string Le SHA de la chaîne
579 function sha256($str, $ig_func = true) { return _nano_sha256($str, $ig_func); }
582 // support to give php4 the hash() routine which abstracts this code.
583 if (!function_exists('hash')) {
584 define('_NO_HASH_DEFINED', true);
586 * Retourne le calcul d'un hachage d'une chaîne (pour PHP4)
588 * @param string $algo Nom de l'algorythme de hachage
589 * @param string $data Chaîne à hacher
590 * @return string|bool
592 * False si pas d'algo trouvé
594 function hash($algo, $data) {
595 if (empty($algo) ||
!is_string($algo) ||
!is_string($data)) {
599 if (function_exists($algo)) {