本文整理汇总了PHP中hash_hmac函数的典型用法代码示例。如果您正苦于以下问题:PHP hash_hmac函数的具体用法?PHP hash_hmac怎么用?PHP hash_hmac使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hash_hmac函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: do_request
/**
* Do CURL request with authorization
*/
private function do_request($resource, $method, $input)
{
$called_url = $this->base_url . "/" . $resource;
$ch = curl_init($called_url);
$c_date_time = date("r");
$md5_content = "";
if ($input != "") {
$md5_content = md5($input);
}
$content_type = "application/json";
$sign_string = $method . "\n" . $md5_content . "\n" . $content_type . "\n" . $c_date_time . "\n" . $called_url;
$time_header = 'X-mailin-date:' . $c_date_time;
$auth_header = 'Authorization:' . $this->access_key . ":" . base64_encode(hash_hmac('sha1', utf8_encode($sign_string), $this->secret_key));
$content_header = "Content-Type:application/json";
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
// Windows only over-ride
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array($time_header, $auth_header, $content_header));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $input);
$data = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch) . '\\n';
}
curl_close($ch);
return json_decode($data, true);
}
示例2: update
public function update()
{
if ($GLOBALS['cached'] == false || $this->_fileHandler->lastTimeModified() >= 30) {
// updates every 30 seconds
$poolData = array();
foreach ($this->_actions as $action) {
$nonce = number_format(time() * mt_rand(), 0, '', '');
$hmacSig = strtoupper(hash_hmac('sha256', $this->_userId . $this->_apiKey . $nonce, $this->_apiSecret));
$postParams = http_build_query(array('key' => $this->_apiKey, 'nonce' => $nonce, 'signature' => $hmacSig));
$poolData[$action] = curlCall($this->_apiURL . '/api/' . $action . '.htm', $postParams, 'application/x-www-form-urlencoded', array('key' => $this->_apiKey, 'sig' => $hmacSig));
$poolData[$action] = $poolData[$action]['data'];
}
// Offline Check
if (empty($poolData[$this->_actions[0]])) {
return;
}
// Data Order
$data['type'] = $this->_type;
$data['sent'] = number_format($poolData['account']['paidOut'], 8);
$data['balance'] = number_format($poolData['account']['balance'], 8);
$data['current_earnings'] = number_format($poolData['account']['earnTotal'], 8);
$data['pool_hashrate'] = formatHashrate($poolData['poolStats']['poolHashrate'] * 1000);
// User Hashrate
$data['user_hashrate_(1_day)'] = formatHashrate($poolData['hashrate']['last1d'] * 1000);
$data['user_hashrate_(1_hour)'] = formatHashrate($poolData['hashrate']['last1h'] * 1000);
$data['user_hashrate_(10_minutes)'] = formatHashrate($poolData['hashrate']['last10m'] * 1000);
$data['eta_on_block'] = formatTimeElapsed($poolData['poolStats']['estimateTime']);
$data['url'] = $this->_apiURL;
$this->_fileHandler->write(json_encode($data));
return $data;
}
return json_decode($this->_fileHandler->read(), true);
}
示例3: _createHash
/**
* @param array $data
* @param string $secret
* @return string
*/
protected function _createHash(array $data, $secret)
{
$time = time();
array_push($data, $time);
$dataString = join('.', $data);
return $time . '.' . hash_hmac('sha256', $dataString, $secret);
}
示例4: sign_request
/**
* Utility function to sign a request
*
* Note this doesn't properly handle the case where a parameter is set both in
* the query string in $url and in $params, or non-scalar values in $params.
*
* @param string $method Generally "GET" or "POST"
* @param string $url URL string
* @param array $params Extra parameters for the Authorization header or post
* data (if application/x-www-form-urlencoded).
* @return string Signature
*/
function sign_request($method, $url, $params = array())
{
global $settings;
$parts = parse_url($url);
// We need to normalize the endpoint URL
$scheme = isset($parts['scheme']) ? $parts['scheme'] : 'http';
$host = isset($parts['host']) ? $parts['host'] : '';
$port = isset($parts['port']) ? $parts['port'] : ($scheme == 'https' ? '443' : '80');
$path = isset($parts['path']) ? $parts['path'] : '';
if ($scheme == 'https' && $port != '443' || $scheme == 'http' && $port != '80') {
// Only include the port if it's not the default
$host = "{$host}:{$port}";
}
// Also the parameters
$pairs = array();
parse_str(isset($parts['query']) ? $parts['query'] : '', $query);
$query += $params;
unset($query['oauth_signature']);
if ($query) {
$query = array_combine(array_map('rawurlencode', array_keys($query)), array_map('rawurlencode', array_values($query)));
ksort($query, SORT_STRING);
foreach ($query as $k => $v) {
$pairs[] = "{$k}={$v}";
}
}
$toSign = rawurlencode(strtoupper($method)) . '&' . rawurlencode("{$scheme}://{$host}{$path}") . '&' . rawurlencode(join('&', $pairs));
$key = rawurlencode($settings['gConsumerSecret']) . '&' . rawurlencode($settings['gTokenSecret']);
return base64_encode(hash_hmac('sha1', $toSign, $key, true));
}
示例5: crypt
/**
* Return a hashed string.
*
* @param string $password
* The string to be hashed.
* @param string $salt
* An optional salt string to base the hashing on. If not provided, a
* suitable string is generated by the adapter.
* @return string
* Returns the hashed string. On failure, a standard crypt error string
* is returned which is guaranteed to differ from the salt.
* @throws RuntimeException
* A RuntimeException is thrown on failure if
* self::$_throwExceptionOnFailure is true.
*/
public function crypt($password, $salt = null)
{
if (!$salt) {
$salt = $this->genSalt();
}
$hash = '*0';
if ($this->verify($salt)) {
$parts = $this->_getSettings($salt);
$rounds = $parts['rounds'];
$checksum = hash_hmac('sha1', $parts['salt'] . '$sha1$' . $parts['rounds'], $password, true);
--$rounds;
if ($rounds) {
do {
$checksum = hash_hmac('sha1', $checksum, $password, true);
} while (--$rounds);
}
// Shuffle the bits around a bit
$tmp = '';
foreach (array(2, 1, 0, 5, 4, 3, 8, 7, 6, 11, 10, 9, 14, 13, 12, 17, 16, 15, 0, 19, 18) as $offset) {
$tmp .= $checksum[$offset];
}
$checksum = $tmp;
$hash = '$sha1$' . $parts['rounds'] . '$' . $parts['salt'] . '$' . $this->_encode64($checksum, 21);
}
if (!$this->verifyHash($hash)) {
$hash = $salt != '*0' ? '*0' : '*1';
if ($this->_throwExceptionOnFailure) {
throw new RuntimeException('Failed generating a valid hash', $hash);
}
}
return $hash;
}
示例6: mtgoxQuery
/**
* Send data to specific mtgox api url
*
* @staticvar null $ch
*
* @param string $path mtgox api path
* @param string $key mtgox key
* @param string $secret mtgox secret key
* @param array $req date to be sent
*
* @return array
* @throws Exception
*/
public function mtgoxQuery($path, $key, $secret, array $req = array())
{
$mt = explode(' ', microtime());
$req['nonce'] = $mt[1] . substr($mt[0], 2, 6);
$postData = http_build_query($req, '', '&');
$headers = array('Rest-Key: ' . $key, 'Rest-Sign: ' . base64_encode(hash_hmac('sha512', $postData, base64_decode($secret), TRUE)));
static $ch = NULL;
if (is_null($ch)) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MtGox PHP client; ' . php_uname('s') . '; PHP/' . phpversion() . ')');
}
curl_setopt($ch, CURLOPT_URL, 'https://mtgox.com/api/' . $path);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$res = curl_exec($ch);
if ($res === FALSE) {
$msg = 'Could not get reply: ' . curl_error($ch);
Mage::log($msg, Zend_Log::ERR);
Mage::getSingleton('core/session')->addError($msg);
}
$dec = json_decode($res, TRUE);
if (!$dec) {
$msg = 'Invalid data received, please make sure connection is working and requested API exists';
Mage::log($msg, Zend_Log::ERR);
Mage::getSingleton('core/session')->addError($msg);
}
return $dec;
}
示例7: _parseSignedRequest
private function _parseSignedRequest()
{
if (!is_string($this->_fbSigs) || empty($this->_fbSigs)) {
$this->isAuthed = false;
throw new SFB_Exception('Invalid Sigs');
}
list($encoded_sig, $payload) = explode('.', $this->_fbSigs, 2);
// decode the data
$sig = $this->_base64UrlDecode($encoded_sig);
$data = json_decode($this->_base64UrlDecode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
$this->isAuthed = false;
throw new SFB_Exception('Invalid Sigs');
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $this->_fbSettings['fbSecret'], $raw = true);
if ($sig !== $expected_sig) {
$this->isAuthed = false;
throw new SFB_Exception('Invalid Sigs');
}
$this->isAuthed = true;
$this->fbSigs = $data;
if (isset($this->fbSigs['oauth_token']) && is_string($this->fbSigs['oauth_token']) && !empty($this->fbSigs['oauth_token'])) {
$this->hasInstalled = true;
}
if (isset($this->fbSigs['user_id']) && is_string($this->fbSigs['user_id']) && !empty($this->fbSigs['user_id'])) {
$this->_fbid = $this->fbSigs['user_id'];
} else {
$this->_fbid = '0';
$this->isAuthed = false;
}
return true;
}
示例8: url
public function url($reference)
{
$timestamp = gmdate('D, d M Y H:i:s T');
$security = base64_encode(hash_hmac('sha256', utf8_encode("{$reference}\n{$timestamp}"), $this->client->api_secret, true));
$data = array('key' => $this->client->api_key, 'timestamp' => $timestamp, 'reference' => $reference, 'security' => $security);
return $this->client->api_endpoint . '/widget?' . http_build_query($data);
}
示例9: hash_hmac
public static function hash_hmac($algo, $data, $key, $raw_output = false)
{
if (function_exists('hash_hmac')) {
return hash_hmac($algo, $data, $key, $raw_output);
}
return self::_hash_hmac($algo, $data, $key, $raw_output);
}
示例10: calculateCode
public function calculateCode($secret, $timeSlice = null)
{
// If we haven't been fed a timeSlice, then get one.
// It looks a bit unclean doing it like this, but it allows us to write testable code
$timeSlice = $timeSlice ? $timeSlice : $this->getTimeSlice();
// Packs the timeslice as a "unsigned long" (always 32 bit, big endian byte order)
$timeSlice = pack("N", $timeSlice);
// Then pad it with the null terminator
$timeSlice = str_pad($timeSlice, 8, chr(0), STR_PAD_LEFT);
// Hash it with SHA1. The spec does offer the idea of other algorithms, but notes that the authenticator is currently
// ignoring it...
$hash = hash_hmac("SHA1", $timeSlice, Base32::decode($secret), true);
// Last 4 bits are an offset apparently
$offset = ord(substr($hash, -1)) & 0xf;
// Grab the last 4 bytes
$result = substr($hash, $offset, 4);
// Unpack it again
$value = unpack('N', $result)[1];
// Only 32 bits
$value = $value & 0x7fffffff;
// Modulo down to the right number of digits
$modulo = pow(10, $this->codeLength);
// Finally, pad out the string with 0s
return str_pad($value % $modulo, $this->codeLength, '0', STR_PAD_LEFT);
}
示例11: calculateRFC2104HMAC
/**
* Computes RFC 2104-compliant HMAC signature.
*
* @param data
* The data to be signed.
* @param key
* The signing key, a.k.a. the AWS secret key.
* @return The base64-encoded RFC 2104-compliant HMAC signature.
*/
public function calculateRFC2104HMAC($data, $key)
{
// compute the hmac on input data bytes, make sure to set returning raw hmac to be true
$rawHmac = hash_hmac(SignatureCalculator::$HMAC_SHA1_ALGORITHM, $data, $key, true);
// base64-encode the raw hmac
return base64_encode($rawHmac);
}
示例12: signature
/**
* Generate a hash signature incorporating a client's secret.
* Based on OAuth 1.0a signature procedure.
*
* @param string|array $content
* @return string
*/
public function signature($content)
{
if (is_array($content)) {
$content = $this->arrayToString($content);
}
return hash_hmac('sha256', $content, $this->client_secret);
}
示例13: generate_signature
/**
* generate_signature - Builds the signature var needed to authenticate
*
* @param int $timestamp
* @returns string URL encoded Signature key/value pair
*/
function generate_signature($timestamp)
{
$timestamp = isset($timestamp) ? $timestamp : time() + 300;
// one minute into the future
$hash = hash_hmac('sha1', $this->access_id . "\n" . $timestamp, $this->secret_key, true);
return urlencode(base64_encode($hash));
}
示例14: decrypt
/**
* Decrypt a string.
*
* @access public
* @static static method
* @param string $ciphertext
* @return string
* @throws Exception If $ciphertext is empty, or If functions don't exists
*/
public static function decrypt($ciphertext)
{
if (empty($ciphertext)) {
throw new Exception("the string to decrypt can't be empty");
}
if (!function_exists('openssl_cipher_iv_length') || !function_exists('openssl_decrypt')) {
throw new Exception("Encryption function don't exists");
}
// generate key used for authentication using ENCRYPTION_KEY & HMAC_SALT
$key = mb_substr(hash(self::HASH_FUNCTION, Config::get('ENCRYPTION_KEY') . Config::get('HMAC_SALT')), 0, 32, '8bit');
// split cipher into: hmac, cipher & iv
$macSize = 64;
$hmac = mb_substr($ciphertext, 0, $macSize, '8bit');
$iv_cipher = mb_substr($ciphertext, $macSize, null, '8bit');
// generate original hmac & compare it with the one in $ciphertext
$originalHmac = hash_hmac('sha256', $iv_cipher, $key);
if (!function_exists("hash_equals")) {
throw new Exception("Function hash_equals() doesn't exist!");
}
if (!hash_equals($hmac, $originalHmac)) {
return false;
}
// split out the initialization vector and cipher
$iv_size = openssl_cipher_iv_length(self::CIPHER);
$iv = mb_substr($iv_cipher, 0, $iv_size, '8bit');
$cipher = mb_substr($iv_cipher, $iv_size, null, '8bit');
return openssl_decrypt($cipher, self::CIPHER, $key, OPENSSL_RAW_DATA, $iv);
}
示例15: _hash
public static function _hash($message)
{
if (!isset(Recurly_js::$privateKey) || strlen(Recurly_js::$privateKey) != 32) {
throw new Recurly_ConfigurationError("Recurly.js private key is not set. The private key must be 32 characters.");
}
return hash_hmac('sha1', $message, Recurly_js::$privateKey);
}