Skip to content

Commit 0c693a4

Browse files
committed
removes unnecessary EC logic
1 parent 107f3c1 commit 0c693a4

File tree

2 files changed

+57
-162
lines changed

2 files changed

+57
-162
lines changed

src/ECPublicKey.php

Lines changed: 0 additions & 161 deletions
This file was deleted.

src/JWT.php

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
*/
2222
class JWT
2323
{
24+
const ASN1_INTEGER = 0x02;
25+
const ASN1_SEQUENCE = 0x10;
2426

2527
/**
2628
* When checking nbf, iat or expiration times,
@@ -99,7 +101,7 @@ public static function decode($jwt, $key, array $allowed_algs = array())
99101
}
100102
if ($header->alg === 'ES256') {
101103
// OpenSSL expects an ASN.1 DER sequence for ES256 signatures
102-
$sig = ECPublicKey::encodeSignature($sig);
104+
$sig = self::encodeSignature($sig);
103105
}
104106

105107
if (is_array($key) || $key instanceof \ArrayAccess) {
@@ -382,4 +384,58 @@ private static function safeStrlen($str)
382384
}
383385
return strlen($str);
384386
}
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+
}
385441
}

0 commit comments

Comments
 (0)