Created
March 8, 2017 14:04
-
-
Save mootari/c7e043c6cc3793b25d0a12d84294ee81 to your computer and use it in GitHub Desktop.
drupal 7 parameter encoding / decoding
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 | |
class MyUtils { | |
public static function getHash($string) { | |
return hash_hmac('sha256', $string, drupal_get_private_key(), false); | |
} | |
/** | |
* Helper function to encode and hash data. | |
*/ | |
public static function encode($data) { | |
$serialized = json_encode($data); | |
$hmac = static::getHash($serialized); | |
$base64 = base64_encode($hmac . ':' . $serialized); | |
return strtr($base64, '+/=', '-_.'); | |
} | |
/** | |
* Helper function to decode and verify data. | |
* | |
* @param string $string | |
* A Base64 encoded string created from | |
* @return mixed|null | |
*/ | |
public static function decode($string) { | |
$string = strtr($string, '-_.', '+/='); | |
$decoded = base64_decode($string); | |
list($hmac, $serialized) = explode(':', $decoded, 2) + array(null, null); | |
if($hmac !== static::getHash($serialized)) { | |
return null; | |
} | |
$data = @json_decode($serialized, true); | |
return $data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment