Skip to content

Instantly share code, notes, and snippets.

@PeeHaa
Created August 1, 2012 13:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PeeHaa/3226920 to your computer and use it in GitHub Desktop.
Save PeeHaa/3226920 to your computer and use it in GitHub Desktop.
Oauth 1a signature example
<?php
/**
* Implementation of the oAuth1 signature spec: http://oauth.net/core/1.0a/ *
*/
namespace Oauth1\Signature;
class TwitterSignature implements \Oauth\Signature
{
protected $signatureAlgorithm;
protected $httpMethod;
protected $authHeader;
protected $body;
protected $requestUri;
public function __construct($signatureAlgorithm, $httpMethod, array $authHeader, $body = null, \Artax\Http\Uri $requestUri)
{
if (!$this->isAlgorithmImplemented($signatureAlgorithm)) {
throw new \Exception('The selected algorithm (`' . $signatureAlgorithm . '`) isn\'t (yet) implemented.');
}
$this->signatureAlgorithm = $signatureAlgorithm;
$this->httpMethod = $httpMethod;
$this->authHeader = $authHeader;
$this->body = $body;
$this->requestUri = $requestUri;
}
protected function isAlgorithmImplemented()
{
$implementedAlgorithms = array('HMAC-SHA1', 'RSA-SHA1');
if (!in_array(strtoupper($this->signatureAlgorithm), $implementedAlgorithms)) {
return false;
}
return true;
}
public function getSignature()
{
return $this->hashString($this->getBaseString(), $this->getSigningKey());
}
protected function getBaseString()
{
return strtoupper($this->httpMethod) . '&' . rawurlencode($this->requestUri) . '&' . rawurlencode($this->getParameterString());
}
protected function getParameterString()
{
$baseStringParts = array();
foreach($this->authHeader as $key => $value) {
if ($key == 'realm') {
continue;
}
$baseStringParts[rawurlencode($key)] = rawurlencode($value);
}
// add $this->body, $this->requestUri
ksort($baseStringParts);
$baseString = '';
$delimiter = '';
foreach($baseStringParts as $key => $value) {
$baseString.= $delimiter . $key . '=' . $value;
$delimiter = '&';
}
return $baseStringParts;
}
protected function getSigningKey()
{
return $this->consumerSecret . '&' . $this->tokenSeret;
}
protected function hashString($string, $key)
{
switch($this->signatureAlgorithm) {
case 'HMAC-SHA1':
return hash_hmac('sha1', $string, $key, true);
case 'RSA-SHA1':
return 'real generate hashed string :-)';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment