|
21 | 21 | */
|
22 | 22 | class JWT
|
23 | 23 | {
|
| 24 | + const ASN1_INTEGER = 0x02; |
| 25 | + const ASN1_SEQUENCE = 0x10; |
24 | 26 |
|
25 | 27 | /**
|
26 | 28 | * When checking nbf, iat or expiration times,
|
@@ -99,7 +101,7 @@ public static function decode($jwt, $key, array $allowed_algs = array())
|
99 | 101 | }
|
100 | 102 | if ($header->alg === 'ES256') {
|
101 | 103 | // OpenSSL expects an ASN.1 DER sequence for ES256 signatures
|
102 |
| - $sig = ECPublicKey::encodeSignature($sig); |
| 104 | + $sig = self::encodeSignature($sig); |
103 | 105 | }
|
104 | 106 |
|
105 | 107 | if (is_array($key) || $key instanceof \ArrayAccess) {
|
@@ -382,4 +384,58 @@ private static function safeStrlen($str)
|
382 | 384 | }
|
383 | 385 | return strlen($str);
|
384 | 386 | }
|
| 387 | + |
| 388 | + /** |
| 389 | + * Convert an ECDSA signature to an ASN.1 DER sequence |
| 390 | + * |
| 391 | + * @param string $sig The ECDSA signature to convert |
| 392 | + * @return string The encoded DER object |
| 393 | + */ |
| 394 | + private static function encodeSignature($sig) |
| 395 | + { |
| 396 | + // Separate the signature into r-value and s-value |
| 397 | + list($r, $s) = str_split($sig, (int) (strlen($sig) / 2)); |
| 398 | + |
| 399 | + // Trim leading zeros |
| 400 | + $r = ltrim($r, "\x00"); |
| 401 | + $s = ltrim($s, "\x00"); |
| 402 | + |
| 403 | + // Convert r-value and s-value from unsigned big-endian integers to |
| 404 | + // signed two's complement |
| 405 | + if (ord($r[0]) > 0x7f) { |
| 406 | + $r = "\x00" . $r; |
| 407 | + } |
| 408 | + if (ord($s[0]) > 0x7f) { |
| 409 | + $s = "\x00" . $s; |
| 410 | + } |
| 411 | + |
| 412 | + return self::encodeDER( |
| 413 | + self::ASN1_SEQUENCE, |
| 414 | + self::encodeDER(self::ASN1_INTEGER, $r) . |
| 415 | + self::encodeDER(self::ASN1_INTEGER, $s) |
| 416 | + ); |
| 417 | + } |
| 418 | + |
| 419 | + /** |
| 420 | + * Encodes a value into a DER object. |
| 421 | + * |
| 422 | + * @param int $type DER tag |
| 423 | + * @param string $value the value to encode |
| 424 | + * @return string the encoded object |
| 425 | + */ |
| 426 | + private static function encodeDER($type, $value) |
| 427 | + { |
| 428 | + $tag_header = 0; |
| 429 | + if ($type === self::ASN1_SEQUENCE) { |
| 430 | + $tag_header |= 0x20; |
| 431 | + } |
| 432 | + |
| 433 | + // Type |
| 434 | + $der = chr($tag_header | $type); |
| 435 | + |
| 436 | + // Length |
| 437 | + $der .= chr(strlen($value)); |
| 438 | + |
| 439 | + return $der . $value; |
| 440 | + } |
385 | 441 | }
|
0 commit comments