/**
  * 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);
 }
Example #2
2
 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);
 }
Example #3
0
 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);
 }
Example #4
0
 /**
  * @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);
 }
Example #5
0
/**
 * 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));
}
Example #6
0
 /**
  * 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;
 }
Example #7
0
 /**
  * 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;
 }
 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;
 }
 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);
 }
 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);
 }
Example #11
0
 /**
  * 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);
 }
 /**
  * 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);
 }
 /**
  * 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));
 }
 /**
  * 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);
 }
Example #15
0
 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);
 }
 function it_compute_payload_with_secret()
 {
     $payload = 'payload';
     $secret = 'secret';
     $signature = hash_hmac('sha1', $payload, $secret);
     $this::compute($payload, $secret)->shouldReturn($signature);
 }
Example #17
0
File: User.php Project: hank/Known
 function post()
 {
     $this->flushBrowser();
     \Idno\Core\site()->logging->log("Loading the user registration callback", LOGLEVEL_DEBUG);
     $contents = $this->getInput('content');
     $auth_token = $this->getInput('auth_token');
     $time = $this->getInput('time');
     $signature = $this->getInput('signature');
     $secret = \Idno\Core\site()->hub()->secret;
     $hmac = hash_hmac('sha1', $contents . $time . $auth_token, $secret);
     if ($hmac == $signature) {
         if ($contents = json_decode($contents)) {
             if (!empty($contents->user)) {
                 if ($user = \Idno\Entities\User::getByUUID($contents->user)) {
                     $user->hub_settings = array('token' => $contents->auth_token, 'secret' => $contents->secret);
                     $user->save();
                     $result = array('status' => 'ok', 'message' => 'Credentials were stored.');
                 } else {
                     $result = array('status' => 'fail', 'message' => 'Couldn\'t find user: '******'status' => 'fail', 'message' => 'No user was sent');
             }
         } else {
             $result = array('status' => 'fail', 'message' => 'Contents were invalid');
         }
     }
     if (empty($result)) {
         $result = array('status' => 'fail', 'message' => 'Signature does not match: ' . $signature . ', ' . $hmac);
     }
     echo json_encode($result);
     exit;
 }
Example #18
0
 /**
  * Generates the fingerprint for request.
  *
  * @param string $merchantApiLoginId
  * @param string $merchantTransactionKey
  * @param string $amount
  * @param string $fpSequence An invoice number or random number.
  * @param string $fpTimestamp
  * @return string The fingerprint.
  */
 public function generateRequestSign($merchantApiLoginId, $merchantTransactionKey, $amount, $currencyCode, $fpSequence, $fpTimestamp)
 {
     if (phpversion() >= '5.1.2') {
         return hash_hmac("md5", $merchantApiLoginId . "^" . $fpSequence . "^" . $fpTimestamp . "^" . $amount . "^" . $currencyCode, $merchantTransactionKey);
     }
     return bin2hex(mhash(MHASH_MD5, $merchantApiLoginId . "^" . $fpSequence . "^" . $fpTimestamp . "^" . $amount . "^" . $currencyCode, $merchantTransactionKey));
 }
    /**
     * admin_auth
     *
     * @return void
     */
    public function auth()
    {
        Configure::write('debug', 0);
        $secretKey = "18sdtadmin40";
        if (!$secretKey) {
            die('{"error" : {"message" : "No secret key set.", "code" : 130}}');
        }
        if (!isset($_REQUEST["hash"]) || !isset($_REQUEST["seed"])) {
            die('{"error" : {"message" : "Error in input.", "code" : 120}}');
        }
        if (!$this->Session->check('Auth.User.id')) {
            die('{"error" : {"message" : "Not authenticated.", "code" : 180}}');
        }
        $hash = $_REQUEST["hash"];
        $seed = $_REQUEST["seed"];
        $localHash = hash_hmac('sha256', $seed, $secretKey);
        if ($hash == $localHash) {
            // Hard code some rootpath, get something from sessions etc.
            die('{"result" : {
  	  	"filesystem.rootpath" : "../../../../webroot/uploads",
  	  	"filesystem.local.wwwroot" : "/full/path/to/public_html/webroot/"
	  	}}');
        } else {
            die('{"error" : {"message" : "Error in input.", "code" : 120}}');
        }
    }
Example #20
0
function make_api_call($url, $http_method, $post_data = array(), $uid = null, $key = null)
{
    $full_url = 'https://app.onepagecrm.com/api/v3/' . $url;
    $ch = curl_init($full_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $http_method);
    $timestamp = time();
    $auth_data = array($uid, $timestamp, $http_method, sha1($full_url));
    $request_headers = array();
    // For POST and PUT requests we will send data as JSON
    // as with regular "form data" request we won't be able
    // to send more complex structures
    if ($http_method == 'POST' || $http_method == 'PUT') {
        $request_headers[] = 'Content-Type: application/json';
        $json_data = json_encode($post_data);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        $auth_data[] = sha1($json_data);
    }
    // Set auth headers if we are logged in
    if ($key != null) {
        $hash = hash_hmac('sha256', implode('.', $auth_data), $key);
        $request_headers[] = "X-OnePageCRM-UID: {$uid}";
        $request_headers[] = "X-OnePageCRM-TS: {$timestamp}";
        $request_headers[] = "X-OnePageCRM-Auth: {$hash}";
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
    $result = json_decode(curl_exec($ch));
    curl_close($ch);
    if ($result->status > 99) {
        echo "API call error: {$result->message}\n";
        return null;
    }
    return $result;
}
 public function isValid()
 {
     $postBody = file_get_contents('php://input');
     $headerHash = $_SERVER['HTTP_X_BLUEDRONE_HOOK_SIGNATURE'];
     $postHash = hash_hmac('SHA256', $postBody, $this->clientSecret);
     return $headerHash === $postHash;
 }
Example #22
0
 /**
  * URL的签名算法,返回一个token字符串
  */
 public static function urlSign($paramArr)
 {
     $options = array('queryParam' => '', 'cryptkey' => '', 'timeInfo' => 0);
     if (is_array($paramArr)) {
         $options = array_merge($options, $paramArr);
     }
     extract($options);
     if (!$queryParam) {
         return '';
     }
     if (is_string($queryParam)) {
         parse_str($queryParam, $queryParam);
     }
     #对参数数组进行排序,保证参数传入的顺序不同,同样能得到结果
     ksort($queryParam);
     $queryString = array();
     foreach ($queryParam as $key => $val) {
         array_push($queryString, $key . '=' . $val);
     }
     $queryString = join('&', $queryString);
     if ($timeInfo) {
         //为了获取时间 可逆
         $queryString .= "#" . time();
         #将时间戳并入
         $sign = self::fastEncode(array('value' => $queryString, 'cryptkey' => $cryptkey));
     } else {
         //没有时间信息 不可逆
         $sign = hash_hmac("sha1", $queryString, $cryptkey);
     }
     return $sign;
 }
/**
 * Get all the necessary details to directly upload a private file to S3
 * asynchronously with JavaScript.
 *
 * @param string $s3Bucket your bucket's name on s3.
 * @param string $region   the bucket's location, see here for details: http://amzn.to/1FtPG6r
 * @param string $acl      the visibility/permissions of your file, see details: http://amzn.to/18s9Gv7
 *
 * @return array ['url', 'inputs'] the forms url to s3 and any inputs the form will need.
 */
function getS3Details($s3Bucket, $region, $acl = 'private')
{
    // Options and Settings
    $algorithm = "AWS4-HMAC-SHA256";
    $service = "s3";
    $date = gmdate('Ymd\\THis\\Z');
    $shortDate = gmdate('Ymd');
    $requestType = "aws4_request";
    $expires = '86400';
    // 24 Hours
    $successStatus = '201';
    $url = '//' . $s3Bucket . '.' . $service . '-' . $region . '.amazonaws.com';
    // Step 1: Generate the Scope
    $scope = [AWS_ACCESS_KEY, $shortDate, $region, $service, $requestType];
    $credentials = implode('/', $scope);
    // Step 2: Making a Base64 Policy
    $policy = ['expiration' => gmdate('Y-m-d\\TG:i:s\\Z', strtotime('+6 hours')), 'conditions' => [['bucket' => $s3Bucket], ['acl' => $acl], ['starts-with', '$key', ''], ['starts-with', '$Content-Type', ''], ['success_action_status' => $successStatus], ['x-amz-credential' => $credentials], ['x-amz-algorithm' => $algorithm], ['x-amz-date' => $date], ['x-amz-expires' => $expires]]];
    $base64Policy = base64_encode(json_encode($policy));
    // Step 3: Signing your Request (Making a Signature)
    $dateKey = hash_hmac('sha256', $shortDate, 'AWS4' . AWS_SECRET, true);
    $dateRegionKey = hash_hmac('sha256', $region, $dateKey, true);
    $dateRegionServiceKey = hash_hmac('sha256', $service, $dateRegionKey, true);
    $signingKey = hash_hmac('sha256', $requestType, $dateRegionServiceKey, true);
    $signature = hash_hmac('sha256', $base64Policy, $signingKey);
    // Step 4: Build form inputs
    // This is the data that will get sent with the form to S3
    $inputs = ['Content-Type' => '', 'acl' => $acl, 'success_action_status' => $successStatus, 'policy' => $base64Policy, 'X-amz-credential' => $credentials, 'X-amz-algorithm' => $algorithm, 'X-amz-date' => $date, 'X-amz-expires' => $expires, 'X-amz-signature' => $signature];
    return compact('url', 'inputs');
}
Example #24
0
 private function _remakeURI($baseurl, $params)
 {
     // Timestamp パラメータを追加します
     // - 時間の表記は ISO8601 形式、タイムゾーンは UTC(GMT)
     $params['Timestamp'] = gmdate('Y-m-d\\TH:i:s\\Z');
     // パラメータの順序を昇順に並び替えます
     ksort($params);
     // canonical string を作成します
     $canonical_string = '';
     foreach ($params as $k => $v) {
         $canonical_string .= '&' . $this->_urlencode_rfc3986($k) . '=' . $this->_urlencode_rfc3986($v);
     }
     $canonical_string = substr($canonical_string, 1);
     // 署名を作成します
     // - 規定の文字列フォーマットを作成
     // - HMAC-SHA256 を計算
     // - BASE64 エンコード
     $parsed_url = parse_url($baseurl);
     $string_to_sign = "GET\n{$parsed_url['host']}\n{$parsed_url['path']}\n{$canonical_string}";
     $signature = base64_encode(hash_hmac('sha256', $string_to_sign, SECRET_KEY, true));
     // URL を作成します
     // - リクエストの末尾に署名を追加
     $url = $baseurl . '?' . $canonical_string . '&Signature=' . $this->_urlencode_rfc3986($signature);
     return $url;
 }
 /**
  * PBKDF2 Implementation for deriving keys.
  *
  * @param   string   $p   Password
  * @param   string   $s   Salt
  * @param   integer  $kl  Key length
  * @param   integer  $c   Iteration count
  * @param   string   $a   Hash algorithm
  *
  * @return  string  The derived key.
  *
  * @see     http://en.wikipedia.org/wiki/PBKDF2
  * @see     http://www.ietf.org/rfc/rfc2898.txt
  * 
  * @copyright   Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
  */
 protected static function pbkdf2($p, $s, $kl, $c = 10000, $a = 'sha256')
 {
     // simple md5 version
     if (!function_exists('hash')) {
         $seed = $p . $s;
         $md5 = md5($seed);
         for ($i = 0; $i < $c; $i++) {
             $md5 = md5($md5 . md5(rand(0, 2147483647)));
         }
         return substr($md5, 0, $kl);
     }
     // Hash length.
     $hl = strlen(hash($a, null, true));
     // Key blocks to compute.
     $kb = ceil($kl / $hl);
     // Derived key.
     $dk = '';
     // Create the key.
     for ($block = 1; $block <= $kb; $block++) {
         // Initial hash for this block.
         $ib = $b = hash_hmac($a, $s . pack('N', $block), $p, true);
         // Perform block iterations.
         for ($i = 1; $i < $c; $i++) {
             $ib ^= $b = hash_hmac($a, $b, $p, true);
         }
         // Append the iterated block.
         $dk .= $ib;
     }
     // Return derived key of correct length.
     return substr($dk, 0, $kl);
 }
Example #26
0
 public static function init()
 {
     global $disqusSecretKey, $disqusPublicKey;
     $userInfo = User::getUserInfo();
     $userID = $userInfo["id"];
     $username = $userInfo["username"];
     $email = $userInfo["email"];
     $data = array("id" => $userID, "username" => $username, "email" => $email);
     $message = base64_encode(json_encode($data));
     $timestamp = time();
     $hmac = hash_hmac("sha1", $message . ' ' . $timestamp, $disqusSecretKey);
     $js = "var disqus_config = function() {\n";
     $js .= "\t\tthis.page.remote_auth_s3 = '{$message} {$hmac} {$timestamp}';\n";
     $js .= "\t\tthis.page.api_key = '{$disqusPublicKey}';\n";
     $js .= "\n";
     $js .= "\t\tthis.sso = {\n";
     $js .= "\t\t\tname: 'zKillboard',\n";
     $js .= "\t\t\tbutton: 'https://zkillboard.com/img/disqus_button.png',\n";
     $js .= "\t\t\ticon: 'https://zkillboard.com/favicon.ico',\n";
     $js .= "\t\t\turl: 'https://zkillboard.com/dlogin/',\n";
     $js .= "\t\t\tlogout: 'https://zkillboard.com/logout',\n";
     $js .= "\t\t\twidth: '300',\n";
     $js .= "\t\t\theight: '232'\n";
     $js .= "\t\t};\n";
     $js .= "\t};";
     return $js;
 }
Example #27
0
 public function buat_SEP()
 {
     $timezone = date_default_timezone_get();
     date_default_timezone_set('UTC');
     $timestamp = strval(time() - strtotime('1970-01-01 00:00:00'));
     //cari timestamp
     $signature = hash_hmac('sha256', '27952' . '&' . $timestamp, 'rsm32h1', true);
     $encoded_signature = base64_encode($signature);
     $http_header = array('Accept: application/json', 'Content-type: application/xml', 'X-cons-id: 27952', 'X-timestamp: ' . $timestamp, 'X-signature: ' . $encoded_signature);
     date_default_timezone_set($timezone);
     //nama variabel sesuai dengan nama di xml
     $noMR = $this->input->post('no_cm');
     $noKartu = $this->input->post('no_bpjs');
     $noRujukan = $this->input->post('no_sjp');
     $ppkRujukan = $this->input->post('ppk_rujukan');
     $jnsPelayanan = $this->input->post('pelayanan');
     $klsRawat = $this->input->post('kelas_pasien');
     $diagAwal = $this->input->post('nm_diagnosa');
     $poliTujuan = $this->input->post('nm_poli');
     $catatan = $this->input->post('catatan');
     $user = '******';
     $ppkPelayanan = '0601R001';
     $tglSep = date('Y-m-d H:i:s');
     $tglRujukan = date('Y-m-d H:i:s');
     $data = '<request><data><t_sep>' . '<noKartu>' . $noKartu . '</noKartu>' . '<tglSep>' . $tglSep . '</tglSep>' . '<tglRujukan>' . $tglRujukan . '</tglRujukan>' . '<noRujukan>' . $noRujukan . '</noRujukan>' . '<ppkRujukan>' . $ppkRujukan . '</ppkRujukan>' . '<ppkPelayanan>' . $ppkPelayanan . '</ppkPelayanan>' . '<jnsPelayanan>' . $jnsPelayanan . '</jnsPelayanan>' . '<catatan>' . $catatan . '</catatan>' . '<diagAwal>' . $diagAwal . '</diagAwal>' . '<poliTujuan>' . $poliTujuan . '</poliTujuan>' . '<klsRawat>' . $klsRawat . '</klsRawat>' . '<user>' . $user . '</user>' . '<noMR>' . $noMR . '</noMR>' . '</t_sep></data></request>';
     $ch = curl_init('http://api.asterix.co.id/SepWebRest/sep/create/');
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $http_header);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $result = curl_exec($ch);
     curl_close($ch);
     $sep = json_decode($result)->response;
     echo $sep;
 }
Example #28
0
function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false)
{
    $algorithm = strtolower($algorithm);
    if (!in_array($algorithm, hash_algos(), true)) {
        die('PBKDF2 ERROR: Invalid hash algorithm.');
    }
    if ($count <= 0 || $key_length <= 0) {
        die('PBKDF2 ERROR: Invalid parameters.');
    }
    $hash_length = strlen(hash($algorithm, "", true));
    $block_count = ceil($key_length / $hash_length);
    $output = "";
    for ($i = 1; $i <= $block_count; $i++) {
        // $i encoded as 4 bytes, big endian.
        $last = $salt . pack("N", $i);
        // first iteration
        $last = $xorsum = hash_hmac($algorithm, $last, $password, true);
        // perform the other $count - 1 iterations
        for ($j = 1; $j < $count; $j++) {
            $xorsum ^= $last = hash_hmac($algorithm, $last, $password, true);
        }
        $output .= $xorsum;
    }
    if ($raw_output) {
        return substr($output, 0, $key_length);
    } else {
        return bin2hex(substr($output, 0, $key_length));
    }
}
Example #29
0
 private static function parse_vals($key, $val, $prefix, $ikey, $time = NULL)
 {
     $ts = $time ? $time : time();
     $parts = explode('|', $val);
     if (count($parts) !== 3) {
         return null;
     }
     list($u_prefix, $u_b64, $u_sig) = $parts;
     $sig = hash_hmac("sha1", $u_prefix . '|' . $u_b64, $key);
     if (hash_hmac("sha1", $sig, $key) !== hash_hmac("sha1", $u_sig, $key)) {
         return null;
     }
     if ($u_prefix !== $prefix) {
         return null;
     }
     $cookie_parts = explode('|', base64_decode($u_b64));
     if (count($cookie_parts) !== 3) {
         return null;
     }
     list($user, $u_ikey, $exp) = $cookie_parts;
     if ($u_ikey !== $ikey) {
         return null;
     }
     if ($ts >= intval($exp)) {
         return null;
     }
     return $user;
 }
 public function generateUserHash($identifier)
 {
     if (defined('INTERCOM_SECRET_KEY')) {
         $secret = INTERCOM_SECRET_KEY;
         return hash_hmac("sha256", $identifier, $secret);
     }
 }