00001 <?php
00026 require_once 'Zend/Crypt.php';
00027
00039 class Zend_Crypt_Hmac extends Zend_Crypt
00040 {
00041
00047 protected static $_key = null;
00048
00054 protected static $_packFormat = null;
00055
00062 protected static $_hashAlgorithm = 'md5';
00063
00069 protected static $_supportedMhashAlgorithms = array('adler32',' crc32', 'crc32b', 'gost',
00070 'haval128', 'haval160', 'haval192', 'haval256', 'md4', 'md5', 'ripemd160',
00071 'sha1', 'sha256', 'tiger', 'tiger128', 'tiger160');
00072
00076 const STRING = 'string';
00077 const BINARY = 'binary';
00078
00091 public static function compute($key, $hash, $data, $output = self::STRING)
00092 {
00093
00094 if (!isset($key) || empty($key)) {
00095 require_once 'Zend/Crypt/Hmac/Exception.php';
00096 throw new Zend_Crypt_Hmac_Exception('provided key is null or empty');
00097 }
00098 self::$_key = $key;
00099
00100
00101 self::_setHashAlgorithm($hash);
00102
00103
00104 return self::_hash($data, $output);
00105 }
00106
00113 protected static function _setHashAlgorithm($hash)
00114 {
00115 if (!isset($hash) || empty($hash)) {
00116 require_once 'Zend/Crypt/Hmac/Exception.php';
00117 throw new Zend_Crypt_Hmac_Exception('provided hash string is null or empty');
00118 }
00119
00120 $hash = strtolower($hash);
00121 $hashSupported = false;
00122
00123 if (function_exists('hash_algos') && in_array($hash, hash_algos())) {
00124 $hashSupported = true;
00125 }
00126
00127 if ($hashSupported === false && function_exists('mhash') && in_array($hash, self::$_supportedAlgosMhash)) {
00128 $hashSupported = true;
00129 }
00130
00131 if ($hashSupported === false) {
00132 require_once 'Zend/Crypt/Hmac/Exception.php';
00133 throw new Zend_Crypt_Hmac_Exception('hash algorithm provided is not supported on this PHP installation; please enable the hash or mhash extensions');
00134 }
00135 self::$_hashAlgorithm = $hash;
00136 }
00137
00146 protected static function _hash($data, $output = self::STRING, $internal = false)
00147 {
00148 if (function_exists('hash_hmac')) {
00149 if ($output == self::BINARY) {
00150 return hash_hmac(self::$_hashAlgorithm, $data, self::$_key, 1);
00151 }
00152 return hash_hmac(self::$_hashAlgorithm, $data, self::$_key);
00153 }
00154
00155 if (function_exists('mhash')) {
00156 if ($output == self::BINARY) {
00157 return mhash(self::_getMhashDefinition(self::$_hashAlgorithm), $data, self::$_key);
00158 }
00159 $bin = mhash(self::_getMhashDefinition(self::$_hashAlgorithm), $data, self::$_key);
00160 return bin2hex($bin);
00161 }
00162 }
00163
00172 protected static function _getMhashDefinition($hashAlgorithm)
00173 {
00174 for ($i = 0; $i <= mhash_count(); $i++)
00175 {
00176 $types[mhash_get_hash_name($i)] = $i;
00177 }
00178 return $types[strtoupper($hashAlgorithm)];
00179 }
00180
00181 }