Created
December 23, 2017 14:44
-
-
Save nilesolutions/e4fea04f4f70af5a981e99e00e5375c1 to your computer and use it in GitHub Desktop.
secrets sharing via token
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 | |
require 'vendor/autoload.php'; | |
function decrypt($secret, $string) | |
{ | |
try { | |
Firebase\JWT\JWT::$leeway = 1; // $leeway in seconds is a clock skew times between the signing and verifying servers | |
$string = base64_decode($string); | |
return (array) Firebase\JWT\JWT::decode( | |
openssl_decrypt( | |
substr($string, 16), | |
'AES-256-CBC', | |
$secret, | |
false, | |
substr($string, 0, 16) | |
), | |
$secret, | |
['HS256'] | |
); | |
} catch (Exception $e) { | |
throw $e; | |
} | |
} | |
function encrypt($secret, $data, $ttl = 3600*24) | |
{ | |
$data = array_merge($data, [ | |
'iat' => time(), // issues at time | |
'exp' => time() + $ttl // expires at time | |
]); | |
$token = Firebase\JWT\JWT::encode($data, $secret); | |
$iv = openssl_random_pseudo_bytes(16); | |
return base64_encode($iv . openssl_encrypt($token, 'AES-256-CBC', $secret, false, $iv)); | |
} | |
// setting the Secret and TimeToLive of session cookie data | |
define('SESSION_COOKIE_NAME', 'XXXSESSID'); | |
define('SECRET', 'sunny@beach'); | |
define('TTL', 3600); | |
// generate new session cookie value | |
$cookieValue = encrypt(SECRET, ['id_customer' => '123e4567-e89b-12d3-a456-426655440000'], TTL); | |
// setting the session cookie on client | |
setcookie(SESSION_COOKIE_NAME, $cookieValue, time() + TTL, '/', 'example.com', true, true); | |
// fetch user data from session cookie | |
//$userId = decrypt(SECRET, $_COOKIE[SESSION_COOKIE_NAME])['id_customer']; | |
echo $cookieValue . "\n";die; | |
print_r(decrypt(SECRET, $cookieValue)['id_customer']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment