Exemplo n.º 1
0
 /**
  * Validate the message originated from MailGun
  * {@link http://documentation.mailgun.net/user_manual.html#securing-webhooks}
  *
  * @return boolean
  */
 protected function validate()
 {
     if (!$this->hasHeader('signature')) {
         return false;
     }
     return $this->getHeader('signature') == Hmac::compute($this->apikey, 'sha256', $this->getHeader('timestamp') . $this->getHeader('token'));
 }
Exemplo n.º 2
0
 /**
  * Add the S3 Authorization signature to the request headers
  *
  * @param  string $method
  * @param  string $path
  * @param  array &$headers
  * @return string
  */
 public function generateSignature($method, $path, &$headers)
 {
     if (!is_array($headers)) {
         $headers = array($headers);
     }
     $type = $md5 = $date = '';
     // Search for the Content-type, Content-MD5 and Date headers
     foreach ($headers as $key => $val) {
         if (strcasecmp($key, 'content-type') == 0) {
             $type = $val;
         } elseif (strcasecmp($key, 'content-md5') == 0) {
             $md5 = $val;
         } elseif (strcasecmp($key, 'date') == 0) {
             $date = $val;
         }
     }
     // If we have an x-amz-date header, use that instead of the normal Date
     if (isset($headers['x-amz-date']) && isset($date)) {
         $date = '';
     }
     $sig_str = "{$method}\n{$md5}\n{$type}\n{$date}\n";
     // For x-amz- headers, combine like keys, lowercase them, sort them
     // alphabetically and remove excess spaces around values
     $amz_headers = array();
     foreach ($headers as $key => $val) {
         $key = strtolower($key);
         if (substr($key, 0, 6) == 'x-amz-') {
             if (is_array($val)) {
                 $amz_headers[$key] = $val;
             } else {
                 $amz_headers[$key][] = preg_replace('/\\s+/', ' ', $val);
             }
         }
     }
     if (!empty($amz_headers)) {
         ksort($amz_headers);
         foreach ($amz_headers as $key => $val) {
             $sig_str .= $key . ':' . implode(',', $val) . "\n";
         }
     }
     $sig_str .= '/' . parse_url($path, PHP_URL_PATH);
     if (strpos($path, '?location') !== false) {
         $sig_str .= '?location';
     } else {
         if (strpos($path, '?acl') !== false) {
             $sig_str .= '?acl';
         } else {
             if (strpos($path, '?torrent') !== false) {
                 $sig_str .= '?torrent';
             }
         }
     }
     $signature = Hmac::compute($this->_secretKey, 'sha1', utf8_encode($sig_str), Hmac::OUTPUT_BINARY);
     $headers['Authorization'] = 'AWS ' . $this->_accessKey . ':' . base64_encode($signature);
     return $sig_str;
 }
Exemplo n.º 3
0
 /**
  * Sign a request
  * 
  * @param  array $params 
  * @param  mixed $method 
  * @param  mixed $url 
  * @return string
  */
 public function sign(array $params, $method = null, $url = null)
 {
     $binaryHash = HMACEncryption::compute(
         $this->_key,
         $this->_hashAlgorithm,
         $this->_getBaseSignatureString($params, $method, $url),
         HMACEncryption::BINARY
     );
     return base64_encode($binaryHash);
 }
Exemplo n.º 4
0
 /**
  * Computes the RFC 2104-compliant HMAC signature for request parameters
  *
  * This implements the Amazon Web Services signature, as per the following
  * specification:
  *
  * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  *    excluding <tt>Signature</tt>, the value of which is being created),
  *    ignoring case.
  *
  * 2. Iterate over the sorted list and append the parameter name (in its
  *    original case) and then its value. Do not URL-encode the parameter
  *    values before constructing this string. Do not use any separator
  *    characters when appending strings.
  *
  * @param string $url Queue URL
  * @param array $parameters the parameters for which to get the signature.
  *
  * @return string the signed data.
  */
 protected function _signParameters($url, array &$parameters)
 {
     $data = '';
     uksort($parameters, 'strcasecmp');
     unset($parameters['Signature']);
     foreach ($parameters as $key => $value) {
         $data .= $key . $value;
     }
     $hmac = Hmac::compute($this->_secretKey, 'SHA1', $data, Hmac::OUTPUT_BINARY);
     $parameters['Signature'] = base64_encode($hmac);
     return $data;
 }
Exemplo n.º 5
0
 /**
  * Generate the new key
  *
  * @param  string  $hash       The hash algorithm to be used by HMAC
  * @param  string  $password   The source password/key
  * @param  string  $salt
  * @param  integer $iterations The number of iterations
  * @param  integer $length     The output size
  * @return string
  */
 public static function calc($hash, $password, $salt, $iterations, $length)
 {
     if (!in_array($hash, Hmac::getSupportedAlgorithms())) {
         throw new Exception\InvalidArgumentException("The hash algorihtm {$hash} is not supported by " . __CLASS__);
     }
     $num = ceil($length / Hmac::getOutputSize($hash, Hmac::BINARY));
     $result = '';
     for ($block = 0; $block < $num; $block++) {
         $hmac = Hmac::compute($password, $hash, $salt . pack('N', $block), Hmac::BINARY);
         for ($i = 1; $i < $iterations; $i++) {
             $hmac ^= Hmac::compute($password, $hash, $hmac, Hmac::BINARY);
         }
         $result .= $hmac;
     }
     return substr($result, 0, $length);
 }
Exemplo n.º 6
0
 /**
  * Generate the new key
  *
  * @param  string  $hash       The hash algorithm to be used by HMAC
  * @param  string  $password   The source password/key
  * @param  string  $salt
  * @param  int $iterations The number of iterations
  * @param  int $length     The output size
  * @throws Exception\InvalidArgumentException
  * @return string
  */
 public static function calc($hash, $password, $salt, $iterations, $length)
 {
     if (!Hmac::isSupported($hash)) {
         throw new Exception\InvalidArgumentException("The hash algorithm {$hash} is not supported by " . __CLASS__);
     }
     $num = ceil($length / Hmac::getOutputSize($hash, Hmac::OUTPUT_BINARY));
     $result = '';
     for ($block = 1; $block <= $num; $block++) {
         $hmac = hash_hmac($hash, $salt . pack('N', $block), $password, Hmac::OUTPUT_BINARY);
         $mix = $hmac;
         for ($i = 1; $i < $iterations; $i++) {
             $hmac = hash_hmac($hash, $hmac, $password, Hmac::OUTPUT_BINARY);
             $mix ^= $hmac;
         }
         $result .= $mix;
     }
     return substr($result, 0, $length);
 }
Exemplo n.º 7
0
 public function testHmacRIPEMD160_7()
 {
     $data = 'Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data';
     $key = str_repeat("ª", 80);
     $hmac = HMAC::compute($key, 'RIPEMD160', $data);
     $this->assertEquals('69ea60798d71616cce5fd0871e23754cd75d5a0a', $hmac);
 }
Exemplo n.º 8
0
 /**
  * Computes the RFC 2104-compliant HMAC signature for request parameters
  *
  * This implements the Amazon Web Services signature, as per the following
  * specification:
  *
  * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  *    excluding <tt>Signature</tt>, the value of which is being created),
  *    ignoring case.
  *
  * 2. Iterate over the sorted list and append the parameter name (in its
  *    original case) and then its value. Do not URL-encode the parameter
  *    values before constructing this string. Do not use any separator
  *    characters when appending strings.
  *
  * @param array  $parameters the parameters for which to get the signature.
  * @param string $secretKey  the secret key to use to sign the parameters.
  *
  * @return string the signed data.
  */
 protected function signParameters(array $paramaters)
 {
     $data = "POST\n";
     $data .= $this->_getRegion() . $this->_ec2Endpoint . "\n";
     $data .= "/\n";
     uksort($paramaters, 'strcmp');
     unset($paramaters['Signature']);
     $arrData = array();
     foreach ($paramaters as $key => $value) {
         $arrData[] = $key . '=' . str_replace("%7E", "~", rawurlencode($value));
     }
     $data .= implode('&', $arrData);
     $hmac = Crypt\Hmac::compute($this->_getSecretKey(), 'SHA256', $data, Crypt\Hmac::BINARY);
     return base64_encode($hmac);
 }
Exemplo n.º 9
0
 /**
  * Add the S3 Authorization signature to the request headers
  *
  * @param  string $method
  * @param  string $path
  * @param  array  $headers
  * @return array
  */
 protected function addSignature($method, $path, $headers)
 {
     if (!is_array($headers)) {
         $headers = array($headers);
     }
     $type = $md5 = $date = '';
     // Search for the Content-type, Content-MD5 and Date headers
     foreach ($headers as $key => $val) {
         if (strcasecmp($key, 'content-type') == 0) {
             $type = $val;
         } elseif (strcasecmp($key, 'content-md5') == 0) {
             $md5 = $val;
         } elseif (strcasecmp($key, 'date') == 0) {
             $date = $val;
         }
     }
     // If we have an x-amz-date header, use that instead of the normal Date
     if (isset($headers['x-amz-date']) && isset($date)) {
         $date = '';
     }
     $sig_str = "{$method}\n{$md5}\n{$type}\n{$date}\n";
     // For x-amz- headers, combine like keys, lowercase them, sort them
     // alphabetically and remove excess spaces around values
     $amz_headers = array();
     foreach ($headers as $key => $val) {
         $key = strtolower($key);
         if (substr($key, 0, 6) == 'x-amz-') {
             if (is_array($val)) {
                 $amz_headers[$key] = $val;
             } else {
                 $amz_headers[$key][] = preg_replace('/\\s+/', ' ', $val);
             }
         }
     }
     if (!empty($amz_headers)) {
         ksort($amz_headers);
         foreach ($amz_headers as $key => $val) {
             $sig_str .= $key . ':' . implode(',', $val) . "\n";
         }
     }
     //US General bucket names must always be lowercased for the signature
     $urlPath = parse_url($path, PHP_URL_PATH);
     $urlPathParts = explode('/', $urlPath);
     if (!empty($urlPathParts[0])) {
         $urlPathParts[0] = strtolower($urlPathParts[0]);
     }
     $sig_str .= '/' . implode('/', $urlPathParts);
     if (strpos($path, '?location') !== false) {
         $sig_str .= '?location';
     } elseif (strpos($path, '?acl') !== false) {
         $sig_str .= '?acl';
     } elseif (strpos($path, '?torrent') !== false) {
         $sig_str .= '?torrent';
     }
     $signature = base64_encode(Hmac::compute($this->_getSecretKey(), 'sha1', utf8_encode($sig_str), true));
     $headers['Authorization'] = 'AWS ' . $this->_getAccessKey() . ':' . $signature;
     return $headers;
 }
Exemplo n.º 10
0
 /**
  * Decrypt
  *
  * @param  string $data
  * @return string|boolean
  * @throws Exception\InvalidArgumentException
  */
 public function decrypt($data)
 {
     if (!is_string($data)) {
         throw new Exception\InvalidArgumentException('The data to decrypt must be a string');
     }
     if ('' === $data) {
         throw new Exception\InvalidArgumentException('The data to decrypt cannot be empty');
     }
     if (empty($this->key)) {
         throw new Exception\InvalidArgumentException('No key specified for the decryption');
     }
     if (empty($this->cipher)) {
         throw new Exception\InvalidArgumentException('No symmetric cipher specified');
     }
     $hmacSize = Hmac::getOutputSize($this->hash);
     $hmac = substr($data, 0, $hmacSize);
     $ciphertext = substr($data, $hmacSize);
     if (!$this->binaryOutput) {
         $ciphertext = base64_decode($ciphertext);
     }
     $iv = substr($ciphertext, 0, $this->cipher->getSaltSize());
     $keySize = $this->cipher->getKeySize();
     // generate the encryption key and the HMAC key for the authentication
     $hash = Pbkdf2::calc(self::KEY_DERIV_HMAC, $this->getKey(), $iv, $this->keyIteration, $keySize * 2);
     // set the decryption key
     $this->cipher->setKey(substr($hash, 0, $keySize));
     // set the key for HMAC
     $keyHmac = substr($hash, $keySize);
     $hmacNew = Hmac::compute($keyHmac, $this->hash, $this->cipher->getAlgorithm() . $ciphertext);
     if (!Utils::compareStrings($hmacNew, $hmac)) {
         return false;
     }
     return $this->cipher->decrypt($ciphertext);
 }
 /**
  * Decrypt a file
  *
  * @param  string                             $fileIn
  * @param  string                             $fileOut
  * @param  bool                               $compress
  * @return bool
  * @throws Exception\InvalidArgumentException
  */
 public function decrypt($fileIn, $fileOut)
 {
     $this->checkFileInOut($fileIn, $fileOut);
     if (empty($this->key)) {
         throw new Exception\InvalidArgumentException('No key specified for decryption');
     }
     $read = fopen($fileIn, "r");
     $write = fopen($fileOut, "w");
     $hmacRead = fread($read, Hmac::getOutputSize($this->getHashAlgorithm()));
     $iv = fread($read, $this->cipher->getSaltSize());
     $tot = filesize($fileIn);
     $hmac = $iv;
     $size = mb_strlen($iv, '8bit') + mb_strlen($hmacRead, '8bit');
     $keys = Pbkdf2::calc($this->getPbkdf2HashAlgorithm(), $this->getKey(), $iv, $this->getKeyIteration(), $this->cipher->getKeySize() * 2);
     $padding = $this->cipher->getPadding();
     $this->cipher->setPadding(new Symmetric\Padding\NoPadding());
     $this->cipher->setKey(mb_substr($keys, 0, $this->cipher->getKeySize(), '8bit'));
     $this->cipher->setMode('cbc');
     $blockSize = $this->cipher->getBlockSize();
     $hashAlgo = $this->getHashAlgorithm();
     $algorithm = $this->cipher->getAlgorithm();
     $saltSize = $this->cipher->getSaltSize();
     $keyHmac = mb_substr($keys, $this->cipher->getKeySize(), null, '8bit');
     while ($data = fread($read, self::BUFFER_SIZE)) {
         $size += mb_strlen($data, '8bit');
         // Unpadding if last block
         if ($size + $blockSize >= $tot) {
             $this->cipher->setPadding($padding);
             $data .= fread($read, $blockSize);
         }
         $result = $this->cipher->decrypt($iv . $data);
         $hmac = Hmac::compute($keyHmac, $hashAlgo, $algorithm . $hmac . $data);
         $iv = mb_substr($data, -1 * $saltSize, null, '8bit');
         if (fwrite($write, $result) !== mb_strlen($result, '8bit')) {
             return false;
         }
     }
     fclose($write);
     fclose($read);
     // check for data integrity
     if (!Utils::compareStrings($hmac, $hmacRead)) {
         unlink($fileOut);
         return false;
     }
     return true;
 }
Exemplo n.º 12
0
 /**
  * Signed S3 Upload Policy
  *
  * @param string $policy            Base64 Encoded string that is the upload policy
  * @return string                   SHA1 encoded S3 Upload Policy
  */
 protected function _signS3UploadPolicy($policy)
 {
     $hmac = Crypt\Hmac::compute($this->_getSecretKey(), 'SHA1', $policy, Crypt\Hmac::BINARY);
     return $hmac;
 }
 public function testTransform()
 {
     $this->assertEquals(Hmac::compute(self::KEY, self::ALGORITHM, self::VALUE, self::BINARY), $this->transformer->transform(self::VALUE));
 }
Exemplo n.º 14
0
 /**
  * Computes the RFC 2104-compliant HMAC signature for request parameters
  *
  * This implements the Amazon Web Services signature, as per the following
  * specification:
  *
  * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  *    excluding <tt>Signature</tt>, the value of which is being created),
  *    ignoring case.
  *
  * 2. Iterate over the sorted list and append the parameter name (in its
  *    original case) and then its value. Do not URL-encode the parameter
  *    values before constructing this string. Do not use any separator
  *    characters when appending strings.
  *
  * @param  string $queue_url  Queue URL
  * @param  array  $parameters the parameters for which to get the signature.
  *
  * @return string the signed data.
  */
 protected function _signParameters($url, array &$paramaters)
 {
     $data = $this->_httpMethod . "\n";
     $data .= parse_url($url, PHP_URL_HOST) . "\n";
     $data .= '' == ($path = parse_url($url, PHP_URL_PATH)) ? '/' : $path;
     $data .= "\n";
     uksort($paramaters, 'strcmp');
     unset($paramaters['Signature']);
     $arrData = array();
     foreach ($paramaters as $key => $value) {
         $arrData[] = $key . '=' . str_replace('%7E', '~', rawurlencode($value));
     }
     $data .= implode('&', $arrData);
     $hmac = Hmac::compute($this->_secretKey, 'SHA256', $data, Hmac::OUTPUT_BINARY);
     $paramaters['Signature'] = base64_encode($hmac);
     return $data;
 }
Exemplo n.º 15
0
 /**
  * Prepare CRAM-MD5 response to server's ticket
  *
  * @param  string $key   Challenge key (usually password)
  * @param  string $data  Challenge data
  * @param  int    $block Length of blocks (deprecated; unused)
  * @return string
  */
 protected function _hmacMd5($key, $data, $block = 64)
 {
     return Hmac::compute($key, 'md5', $data);
 }
Exemplo n.º 16
0
 public function testBinaryOutput()
 {
     $data = Hmac::compute('key', 'sha256', 'test', Hmac::OUTPUT_BINARY);
     $this->assertEquals('Aq+1YwSQLGVvy3N83QPeYgW7bUAdooEu/ZstNqCK8Vk=', base64_encode($data));
 }
Exemplo n.º 17
0
 /**
  * Compute Signature for Authentication with Amazon Product Advertising Webservices
  *
  * @param  string $baseUri
  * @param  string $secretKey
  * @param  array $options
  * @return string
  */
 public static function computeSignature($baseUri, $secretKey, array $options)
 {
     $signature = self::buildRawSignature($baseUri, $options);
     return base64_encode(Hmac::compute($secretKey, 'sha256', $signature, Hmac::OUTPUT_BINARY));
 }
Exemplo n.º 18
0
 /**
  * Computes the RFC 2104-compliant HMAC signature for request parameters
  *
  * This implements the Amazon Web Services signature, as per the following
  * specification:
  *
  * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  *    excluding <tt>Signature</tt>, the value of which is being created),
  *    ignoring case.
  *
  * 2. Iterate over the sorted list and append the parameter name (in its
  *    original case) and then its value. Do not URL-encode the parameter
  *    values before constructing this string. Do not use any separator
  *    characters when appending strings.
  *
  * @param array  $parameters the parameters for which to get the signature.
  *
  * @return string the signed data.
  */
 protected function _signParameters(array $parameters)
 {
     $data = "POST\n";
     $data .= $this->getEndpoint()->getHost() . "\n";
     $data .= "/\n";
     uksort($parameters, 'strcmp');
     unset($parameters['Signature']);
     $arrData = array();
     foreach ($parameters as $key => $value) {
         $value = urlencode($value);
         $value = str_replace("%7E", "~", $value);
         $value = str_replace("+", "%20", $value);
         $arrData[] = urlencode($key) . '=' . $value;
     }
     $data .= implode('&', $arrData);
     $hmac = Hmac::compute($this->_getSecretKey(), 'SHA256', $data, Hmac::OUTPUT_BINARY);
     return base64_encode($hmac);
 }
Exemplo n.º 19
0
 /**
  * Signed S3 Upload Policy
  *
  * @param string $policy Base64 Encoded string that is the upload policy
  * @return string        SHA1 encoded S3 Upload Policy
  */
 protected function _signS3UploadPolicy($policy)
 {
     return Hmac::compute($this->_getSecretKey(), 'SHA1', $policy, Hmac::OUTPUT_BINARY);
 }
Exemplo n.º 20
0
Arquivo: Sqs.php Projeto: rikaix/zf2
 /**
  * Computes the RFC 2104-compliant HMAC signature for request parameters
  *
  * This implements the Amazon Web Services signature, as per the following
  * specification:
  *
  * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  *    excluding <tt>Signature</tt>, the value of which is being created),
  *    ignoring case.
  *
  * 2. Iterate over the sorted list and append the parameter name (in its
  *    original case) and then its value. Do not URL-encode the parameter
  *    values before constructing this string. Do not use any separator
  *    characters when appending strings.
  *
  * @param  string $queue_url  Queue URL
  * @param  array  $parameters the parameters for which to get the signature.
  *
  * @return string the signed data.
  */
 protected function _signParameters($queue_url, array $paramaters)
 {
     $data = "GET\n";
     $data .= $this->_sqsEndpoint . "\n";
     if ($queue_url !== null) {
         $data .= parse_url($queue_url, PHP_URL_PATH);
     } else {
         $data .= '/';
     }
     $data .= "\n";
     uksort($paramaters, 'strcmp');
     unset($paramaters['Signature']);
     $arrData = array();
     foreach ($paramaters as $key => $value) {
         $arrData[] = $key . '=' . str_replace('%7E', '~', urlencode($value));
     }
     $data .= implode('&', $arrData);
     $hmac = Crypt\Hmac::compute($this->_getSecretKey(), 'SHA256', $data, Crypt\Hmac::BINARY);
     return base64_encode($hmac);
 }
 /**
  * @param string $value
  * @return string
  */
 public function transform($value)
 {
     return Hmac::compute($this->key, $this->algorithm, $value, $this->binary);
 }