Last active
August 29, 2015 14:25
-
-
Save LeeSaferite/b885e0359186241b09ff to your computer and use it in GitHub Desktop.
Parameter Encoder and Hasher
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 | |
/** | |
* @param array $parameters | |
* @param string $secretKey | |
* | |
* @return string | |
* | |
* @throws InvalidArgumentException | |
*/ | |
function prepareParameters(array $parameters, $secretKey) | |
{ | |
// Verify a secret key was passed | |
if (empty($secretKey)) { | |
throw new InvalidArgumentException('Secret Key is required!'); | |
} | |
// Encode parameters | |
$parameters = json_encode($parameters, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); | |
// Generate hash | |
$hash = sha1($secretKey . $parameters); | |
// Generate and return token | |
return base64_encode($hash . '|' . $parameters); | |
} | |
/** | |
* @param string $token Token created by prepareParameters() | |
* @param string $secretKey Secret key used when creating token | |
* | |
* @return array|false | |
* | |
* @throws InvalidArgumentException | |
*/ | |
function retrieveParameters($token, $secretKey) | |
{ | |
// Verify a secret key was passed | |
if (empty($secretKey)) { | |
throw new InvalidArgumentException('Secret Key is required!'); | |
} | |
// Parse and extract parameters | |
$parts = explode('|', base64_decode($token), 2); | |
if (count($parts) !== 2) { | |
return false; | |
} | |
$hash = $parts[0]; | |
$parameters = $parts[1]; | |
// Check hash | |
if ($hash !== sha1($secretKey . $parameters)) { | |
return false; | |
} | |
// Return decoded parameters | |
return json_decode($parameters, true, 512, JSON_BIGINT_AS_STRING); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment