1<?php 2 3/** 4 * This is the HMACSHA1 implementation for the OpenID library. 5 * 6 * PHP versions 4 and 5 7 * 8 * LICENSE: See the COPYING file included in this distribution. 9 * 10 * @access private 11 * @package OpenID 12 * @author JanRain, Inc. <openid@janrain.com> 13 * @copyright 2005-2008 Janrain, Inc. 14 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache 15 */ 16 17require_once 'Auth/OpenID.php'; 18 19/** 20 * SHA1_BLOCKSIZE is this module's SHA1 blocksize used by the fallback 21 * implementation. 22 */ 23define('Auth_OpenID_SHA1_BLOCKSIZE', 64); 24 25function Auth_OpenID_SHA1($text) 26{ 27 if (function_exists('hash') && 28 function_exists('hash_algos') && 29 (in_array('sha1', hash_algos()))) { 30 // PHP 5 case (sometimes): 'hash' available and 'sha1' algo 31 // supported. 32 return hash('sha1', $text, true); 33 } else if (function_exists('sha1')) { 34 // PHP 4 case: 'sha1' available. 35 $hex = sha1($text); 36 $raw = ''; 37 for ($i = 0; $i < 40; $i += 2) { 38 $hexcode = substr($hex, $i, 2); 39 $charcode = (int)base_convert($hexcode, 16, 10); 40 $raw .= chr($charcode); 41 } 42 return $raw; 43 } else { 44 // Explode. 45 trigger_error('No SHA1 function found', E_USER_ERROR); 46 return false; 47 } 48} 49 50/** 51 * Compute an HMAC/SHA1 hash. 52 * 53 * @access private 54 * @param string $key The HMAC key 55 * @param string $text The message text to hash 56 * @return string $mac The MAC 57 */ 58function Auth_OpenID_HMACSHA1($key, $text) 59{ 60 if (Auth_OpenID::bytes($key) > Auth_OpenID_SHA1_BLOCKSIZE) { 61 $key = Auth_OpenID_SHA1($key); 62 } 63 64 if (function_exists('hash_hmac') && 65 function_exists('hash_algos') && 66 (in_array('sha1', hash_algos()))) { 67 return hash_hmac('sha1', $text, $key, true); 68 } 69 // Home-made solution 70 71 $key = str_pad($key, Auth_OpenID_SHA1_BLOCKSIZE, chr(0x00)); 72 $ipad = str_repeat(chr(0x36), Auth_OpenID_SHA1_BLOCKSIZE); 73 $opad = str_repeat(chr(0x5c), Auth_OpenID_SHA1_BLOCKSIZE); 74 $hash1 = Auth_OpenID_SHA1(($key ^ $ipad) . $text); 75 $hmac = Auth_OpenID_SHA1(($key ^ $opad) . $hash1); 76 return $hmac; 77} 78 79if (function_exists('hash') && 80 function_exists('hash_algos') && 81 (in_array('sha256', hash_algos()))) { 82 function Auth_OpenID_SHA256($text) 83 { 84 // PHP 5 case: 'hash' available and 'sha256' algo supported. 85 return hash('sha256', $text, true); 86 } 87 define('Auth_OpenID_SHA256_SUPPORTED', true); 88} else { 89 define('Auth_OpenID_SHA256_SUPPORTED', false); 90} 91 92if (function_exists('hash_hmac') && 93 function_exists('hash_algos') && 94 (in_array('sha256', hash_algos()))) { 95 96 function Auth_OpenID_HMACSHA256($key, $text) 97 { 98 // Return raw MAC (not hex string). 99 return hash_hmac('sha256', $text, $key, true); 100 } 101 102 define('Auth_OpenID_HMACSHA256_SUPPORTED', true); 103} else { 104 define('Auth_OpenID_HMACSHA256_SUPPORTED', false); 105} 106 107