44 'ES256' => array(
'openssl',
'SHA256'),
45 'HS256' => array(
'hash_hmac',
'SHA256'),
46 'HS384' => array(
'hash_hmac',
'SHA384'),
47 'HS512' => array(
'hash_hmac',
'SHA512'),
48 'RS256' => array(
'openssl',
'SHA256'),
49 'RS384' => array(
'openssl',
'SHA384'),
50 'RS512' => array(
'openssl',
'SHA512'),
69 public static function decode($jwt, $key, array $allowed_algs = array())
71 $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;
74 throw new InvalidArgumentException(
'Key may not be empty');
76 $tks = explode(
'.', $jwt);
77 if (count($tks) != 3) {
78 throw new UnexpectedValueException(
'Wrong number of segments');
80 list($headb64, $bodyb64, $cryptob64) = $tks;
81 if (
null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) {
82 throw new UnexpectedValueException(
'Invalid header encoding');
84 if (
null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) {
85 throw new UnexpectedValueException(
'Invalid claims encoding');
87 if (
false === ($sig = static::urlsafeB64Decode($cryptob64))) {
88 throw new UnexpectedValueException(
'Invalid signature encoding');
90 if (empty($header->alg)) {
91 throw new UnexpectedValueException(
'Empty algorithm');
93 if (empty(static::$supported_algs[$header->alg])) {
94 throw new UnexpectedValueException(
'Algorithm not supported');
96 if (!in_array($header->alg, $allowed_algs)) {
97 throw new UnexpectedValueException(
'Algorithm not allowed');
99 if ($header->alg ===
'ES256') {
101 $sig = self::signatureToDER($sig);
104 if (is_array($key) || $key instanceof \ArrayAccess) {
105 if (isset($header->kid)) {
106 if (!isset($key[$header->kid])) {
107 throw new UnexpectedValueException(
'"kid" invalid, unable to lookup correct key');
109 $key = $key[$header->kid];
111 throw new UnexpectedValueException(
'"kid" empty, unable to lookup correct key');
116 if (!static::verify(
"$headb64.$bodyb64", $sig, $key, $header->alg)) {
117 throw new UnexpectedValueException(
'Signature verification failed');
122 if (isset($payload->nbf) && $payload->nbf > (
$timestamp + static::$leeway)) {
123 throw new UnexpectedValueException(
124 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
131 if (isset($payload->iat) && $payload->iat > (
$timestamp + static::$leeway)) {
132 throw new UnexpectedValueException(
133 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
138 if (isset($payload->exp) && (
$timestamp - static::$leeway) >= $payload->exp) {
139 throw new UnexpectedValueException(
'Expired token');
161 public static function encode($payload, $key, $alg =
'HS256', $keyId =
null, $head =
null)
163 $header = array(
'typ' =>
'JWT',
'alg' => $alg);
164 if ($keyId !==
null) {
165 $header[
'kid'] = $keyId;
167 if (isset($head) && is_array($head)) {
168 $header = array_merge($head, $header);
171 $segments[] = static::urlsafeB64Encode(static::jsonEncode($header));
172 $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload));
173 $signing_input = implode(
'.', $segments);
175 $signature = static::sign($signing_input, $key, $alg);
176 $segments[] = static::urlsafeB64Encode($signature);
178 return implode(
'.', $segments);
193 public static function sign($msg, $key, $alg =
'HS256')
195 if (empty(static::$supported_algs[$alg])) {
196 throw new DomainException(
'Algorithm not supported');
198 list($function, $algorithm) = static::$supported_algs[$alg];
201 return hash_hmac($algorithm, $msg, $key,
true);
204 $success = openssl_sign($msg, $signature, $key, $algorithm);
206 throw new DomainException(
"OpenSSL unable to sign data");
208 if ($alg ===
'ES256') {
209 $signature = self::signatureFromDER($signature, 256);
229 private static function verify($msg, $signature, $key, $alg)
231 if (empty(static::$supported_algs[$alg])) {
232 throw new DomainException(
'Algorithm not supported');
235 list($function, $algorithm) = static::$supported_algs[$alg];
238 $success = openssl_verify($msg, $signature, $key, $algorithm);
239 if ($success === 1) {
241 } elseif ($success === 0) {
245 throw new DomainException(
246 'OpenSSL error: ' . openssl_error_string()
250 $hash = hash_hmac($algorithm, $msg, $key,
true);
251 if (function_exists(
'hash_equals')) {
252 return hash_equals($signature, $hash);
254 $len = min(strlen($signature), strlen($hash));
257 for ($i = 0; $i < $len; $i++) {
258 $status |= (ord($signature[$i]) ^ ord($hash[$i]));
260 $status |= (strlen($signature) ^ strlen($hash));
262 return ($status === 0);
277 if (version_compare(PHP_VERSION,
'5.4.0',
'>=') && !(defined(
'JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
282 $obj = json_decode($input,
false, 512, JSON_BIGINT_AS_STRING);
288 $max_int_length = strlen((
string) PHP_INT_MAX) - 1;
289 $json_without_bigints = preg_replace(
'/:\s*(-?\d{'.$max_int_length.
',})/',
': "$1"', $input);
290 $obj = json_decode($json_without_bigints);
293 if ($errno = json_last_error()) {
294 static::handleJsonError($errno);
295 } elseif ($obj ===
null && $input !==
'null') {
296 throw new DomainException(
'Null result with non-null input');
312 $json = json_encode($input);
313 if ($errno = json_last_error()) {
314 static::handleJsonError($errno);
315 } elseif ($json ===
'null' && $input !==
null) {
316 throw new DomainException(
'Null result with non-null input');
330 $remainder = strlen($input) % 4;
332 $padlen = 4 - $remainder;
333 $input .= str_repeat(
'=', $padlen);
335 return base64_decode(strtr($input,
'-_',
'+/'));
347 return str_replace(
'=',
'', strtr(base64_encode($input),
'+/',
'-_'));
357 private static function handleJsonError($errno)
360 JSON_ERROR_DEPTH =>
'Maximum stack depth exceeded',
361 JSON_ERROR_STATE_MISMATCH =>
'Invalid or malformed JSON',
362 JSON_ERROR_CTRL_CHAR =>
'Unexpected control character found',
363 JSON_ERROR_SYNTAX =>
'Syntax error, malformed JSON',
364 JSON_ERROR_UTF8 =>
'Malformed UTF-8 characters'
366 throw new DomainException(
367 $messages[$errno] ??
'Unknown JSON error: '.$errno
377 private static function signatureToDER($sig)
380 list($r, $s) = str_split($sig, (
int) (strlen($sig) / 2));
383 $r = ltrim($r,
"\x00");
384 $s = ltrim($s,
"\x00");
388 if (ord($r[0]) > 0x7f) {
391 if (ord($s[0]) > 0x7f) {
395 return self::encodeDER(
397 self::encodeDER(self::ASN1_INTEGER, $r) .
398 self::encodeDER(self::ASN1_INTEGER, $s)
409 private static function encodeDER($type, $value)
412 if ($type === self::ASN1_SEQUENCE) {
417 $der = chr($tag_header | $type);
420 $der .= chr(strlen($value));
422 return $der . $value;
432 private static function signatureFromDER($der, $keySize)
435 list($offset, $_) = self::readDER($der);
436 list($offset, $r) = self::readDER($der, $offset);
437 list($offset, $s) = self::readDER($der, $offset);
441 $r = ltrim($r,
"\x00");
442 $s = ltrim($s,
"\x00");
445 $r = str_pad($r, $keySize / 8,
"\x00", STR_PAD_LEFT);
446 $s = str_pad($s, $keySize / 8,
"\x00", STR_PAD_LEFT);
459 private static function readDER($der, $offset = 0)
462 $size = strlen($der);
463 $constructed = (ord($der[$pos]) >> 5) & 0x01;
464 $type = ord($der[$pos++]) & 0x1f;
467 $len = ord($der[$pos++]);
471 while ($n-- && $pos < $size) {
472 $len = ($len << 8) | ord($der[$pos++]);
477 if ($type == self::ASN1_BIT_STRING) {
479 $data = substr($der, $pos, $len - 1);
481 } elseif (!$constructed) {
482 $data = substr($der, $pos, $len);
488 return array($pos, $data);
static jsonDecode($input)
static urlsafeB64Encode($input)
static decode($jwt, $key, array $allowed_algs=array())
static urlsafeB64Decode($input)
static jsonEncode($input)
static encode($payload, $key, $alg='HS256', $keyId=null, $head=null)
static sign($msg, $key, $alg='HS256')