11 public function encode($payload, $key, $algo =
'HS256')
20 $signing_input = implode(
'.', $segments);
22 $signature = $this->sign($signing_input, $key, $algo);
23 $segments[] = $this->urlsafeB64Encode($signature);
25 return implode(
'.', $segments);
28 public function decode($jwt, $key =
null, $allowedAlgorithms =
true)
30 if (!strpos($jwt,
'.')) {
34 $tks = explode(
'.', $jwt);
36 if (count($tks) != 3) {
40 list($headb64, $payloadb64, $cryptob64) = $tks;
42 if (
null === ($header = json_decode($this->
urlSafeB64Decode($headb64),
true))) {
46 if (
null === $payload = json_decode($this->
urlSafeB64Decode($payloadb64),
true)) {
52 if ((
bool) $allowedAlgorithms) {
53 if (!isset($header[
'alg'])) {
58 if (is_array($allowedAlgorithms) && !in_array($header[
'alg'], $allowedAlgorithms)) {
62 if (!$this->verifySignature($sig,
"$headb64.$payloadb64", $key, $header[
'alg'])) {
70 private function verifySignature($signature, $input, $key, $algo =
'HS256')
78 $this->sign($input, $key, $algo),
83 return openssl_verify($input, $signature, $key, defined(
'OPENSSL_ALGO_SHA256') ? OPENSSL_ALGO_SHA256 :
'sha256') === 1;
86 return @openssl_verify($input, $signature, $key, defined(
'OPENSSL_ALGO_SHA384') ? OPENSSL_ALGO_SHA384 :
'sha384') === 1;
89 return @openssl_verify($input, $signature, $key, defined(
'OPENSSL_ALGO_SHA512') ? OPENSSL_ALGO_SHA512 :
'sha512') === 1;
92 throw new \InvalidArgumentException(
"Unsupported or invalid signing algorithm.");
96 private function sign($input, $key, $algo =
'HS256')
100 return hash_hmac(
'sha256', $input, $key,
true);
103 return hash_hmac(
'sha384', $input, $key,
true);
106 return hash_hmac(
'sha512', $input, $key,
true);
109 return $this->generateRSASignature($input, $key, defined(
'OPENSSL_ALGO_SHA256') ? OPENSSL_ALGO_SHA256 :
'sha256');
112 return $this->generateRSASignature($input, $key, defined(
'OPENSSL_ALGO_SHA384') ? OPENSSL_ALGO_SHA384 :
'sha384');
115 return $this->generateRSASignature($input, $key, defined(
'OPENSSL_ALGO_SHA512') ? OPENSSL_ALGO_SHA512 :
'sha512');
118 throw new \Exception(
"Unsupported or invalid signing algorithm.");
122 private function generateRSASignature($input, $key, $algo)
124 if (!openssl_sign($input, $signature, $key, $algo)) {
125 throw new \Exception(
"Unable to sign data.");
133 $b64 = base64_encode($data);
134 $b64 = str_replace(array(
'+',
'/',
"\r",
"\n",
'='),
143 $b64 = str_replace(array(
'-',
'_'),
147 return base64_decode($b64);
163 if (function_exists(
'hash_equals')) {
166 $diff = strlen($a) ^ strlen($b);
167 for ($i = 0; $i < strlen($a) && $i < strlen($b); $i++) {
168 $diff |= ord($a[$i]) ^ ord($b[$i]);