Created
April 11, 2016 14:18
-
-
Save yoye/9e1e001bb169534af7c07e7fc66a7766 to your computer and use it in GitHub Desktop.
Simple URL signature
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Http\Security; | |
class SignatureProvider | |
{ | |
private $key; | |
private $algorithm; | |
private $timeValidity; | |
public function __construct($key, $algorithm, $timeValidity) | |
{ | |
$this->key = $key; | |
$this->algorithm = $algorithm; | |
$this->timeValidity = $timeValidity; | |
} | |
public function generateSignature($url, $parameters = []) | |
{ | |
$parameters['nonce'] = time(); | |
$signedData = base64_encode(http_build_query($parameters)); | |
$signature = hash_hmac($this->algorithm, $signedData, $this->key); | |
$query = parse_url($url, PHP_URL_QUERY); | |
return $url . (null === $query ? '?' : '&') . http_build_query(['signed_data' => $signedData, 'signature' => $signature]); | |
} | |
public function isSignatureValid($url) | |
{ | |
$query = parse_url($url, PHP_URL_QUERY); | |
parse_str($query, $parameters); | |
if (!array_key_exists('signature', $parameters)) { | |
return false; | |
} | |
if (!array_key_exists('signed_data', $parameters)) { | |
return false; | |
} | |
parse_str(base64_decode($parameters['signed_data']), $signedData); | |
if (!array_key_exists('nonce', $signedData)) { | |
return false; | |
} | |
if ($signedData['nonce'] > time()) { | |
return false; | |
} | |
if ($signedData['nonce'] < time() - $this->timeValidity) { | |
return false; | |
} | |
if ($parameters['signature'] !== hash_hmac($this->algorithm, $parameters['signed_data'], $this->key)) { | |
return false; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment