Skip to content

Commit b31429e

Browse files
committed
Update JWT.php
Try to add the RS256 algorithm.
1 parent 269eca3 commit b31429e

File tree

1 file changed

+40
-10
lines changed

1 file changed

+40
-10
lines changed

Authentication/JWT.php

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,12 @@
2626
*/
2727
class JWT
2828
{
29-
29+
static $methods = array(
30+
'HS256' => array('hash_hmac', 'SHA256'),
31+
'HS512' => array('hash_hmac', 'SHA512'),
32+
'HS384' => array('hash_hmac', 'SHA384'),
33+
'RS256' => array('openssl', 'SHA256'),
34+
);
3035
/**
3136
* Returns just the header portion of the jwt. This allows
3237
* you to determine which key should be used to verify
@@ -80,7 +85,7 @@ public static function decode($jwt, $key = null, $verify = true)
8085
if (empty($header->alg)) {
8186
throw new DomainException('Empty algorithm');
8287
}
83-
if ($sig != JWT::sign("$headb64.$bodyb64", $key, $header->alg)) {
88+
if (!JWT::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
8489
throw new UnexpectedValueException('Signature verification failed');
8590
}
8691
// Check token expiry time if defined.
@@ -131,16 +136,41 @@ public static function encode($payload, $key, $algo = 'HS256')
131136
*/
132137
public static function sign($msg, $key, $method = 'HS256')
133138
{
134-
$methods = array(
135-
'HS256' => 'sha256',
136-
'HS384' => 'sha384',
137-
'HS512' => 'sha512',
138-
);
139-
if (empty($methods[$method])) {
139+
if (empty(self::$methods[$method])) {
140+
throw new DomainException('Algorithm not supported');
141+
}
142+
list($function, $algo) = self::$methods[$method];
143+
switch($function) {
144+
case 'hash_hmac':
145+
return hash_hmac($algo, $msg, $key, true);
146+
case 'openssl':
147+
$signature = '';
148+
$success = openssl_sign($msg, $signature, $key, $algo);
149+
if(!$success) {
150+
throw new DomainException("OpenSSL unable to sign data");
151+
} else {
152+
return $signature;
153+
}
154+
}
155+
}
156+
157+
public static function verify($msg, $signature $key, $method = 'HS256') {
158+
if (empty(self::$methods[$method])) {
140159
throw new DomainException('Algorithm not supported');
141160
}
142-
143-
return hash_hmac($methods[$method], $msg, $key, true);
161+
list($function, $algo) = self::$methods[$method];
162+
switch($function) {
163+
case 'openssl':
164+
$success = openssl_verify($msg, $signature, $key, $algo);
165+
if(!$success) {
166+
throw new DomainException("OpenSSL unable to sign data");
167+
} else {
168+
return $signature;
169+
}
170+
case 'hash_hmac':
171+
default:
172+
return $signature === hash_hmac($algo, $msg, $key, true);
173+
}
144174
}
145175

146176
/**

0 commit comments

Comments
 (0)