|
26 | 26 | */
|
27 | 27 | class JWT
|
28 | 28 | {
|
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 | + ); |
30 | 35 | /**
|
31 | 36 | * Returns just the header portion of the jwt. This allows
|
32 | 37 | * you to determine which key should be used to verify
|
@@ -80,7 +85,7 @@ public static function decode($jwt, $key = null, $verify = true)
|
80 | 85 | if (empty($header->alg)) {
|
81 | 86 | throw new DomainException('Empty algorithm');
|
82 | 87 | }
|
83 |
| - if ($sig != JWT::sign("$headb64.$bodyb64", $key, $header->alg)) { |
| 88 | + if (!JWT::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) { |
84 | 89 | throw new UnexpectedValueException('Signature verification failed');
|
85 | 90 | }
|
86 | 91 | // Check token expiry time if defined.
|
@@ -131,16 +136,41 @@ public static function encode($payload, $key, $algo = 'HS256')
|
131 | 136 | */
|
132 | 137 | public static function sign($msg, $key, $method = 'HS256')
|
133 | 138 | {
|
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])) { |
140 | 159 | throw new DomainException('Algorithm not supported');
|
141 | 160 | }
|
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 | + } |
144 | 174 | }
|
145 | 175 |
|
146 | 176 | /**
|
|
0 commit comments