|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Simples\Security; |
| 4 | + |
| 5 | +use Simples\Helper\JSON; |
| 6 | +use Simples\Http\Error\SimplesForbiddenError; |
| 7 | + |
| 8 | +/** |
| 9 | + * Class Jwt |
| 10 | + * @package Simples\Security |
| 11 | + */ |
| 12 | +abstract class JWT |
| 13 | +{ |
| 14 | + /** |
| 15 | + * @param array $data |
| 16 | + * @param string $secret |
| 17 | + * @return string |
| 18 | + */ |
| 19 | + public static function create(array $data, string $secret): string |
| 20 | + { |
| 21 | + $header = base64_encode(json_encode(['type' => 'JWT', 'alg' => 'HS256'])); |
| 22 | + |
| 23 | + $payload = base64_encode(Encryption::encode(JSON::encode($data), $secret)); |
| 24 | + |
| 25 | + $signature = base64_encode(hash_hmac('sha256', "{$header}.{$payload}", $secret, true)); |
| 26 | + |
| 27 | + return "{$header}.{$payload}.{$signature}"; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * @param string $token |
| 32 | + * @param string $secret |
| 33 | + * @return array |
| 34 | + * @throws SimplesForbiddenError |
| 35 | + */ |
| 36 | + public static function payload(string $token, string $secret): array |
| 37 | + { |
| 38 | + if (!static::verify($token, $secret)) { |
| 39 | + throw new SimplesForbiddenError("The token '{$token}' is invalid"); |
| 40 | + } |
| 41 | + $peaces = explode('.', $token); |
| 42 | + if (count($peaces) !== 3) { |
| 43 | + throw new SimplesForbiddenError("The token '{$token}' is invalid"); |
| 44 | + } |
| 45 | + return (array)JSON::decode(Encryption::decode(base64_decode($peaces[1]), $secret)); |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * @param string $token |
| 50 | + * @param string $secret |
| 51 | + * @return bool |
| 52 | + */ |
| 53 | + public static function verify(string $token, string $secret): bool |
| 54 | + { |
| 55 | + $peaces = explode('.', $token); |
| 56 | + if (count($peaces) < 3) { |
| 57 | + return false; |
| 58 | + } |
| 59 | + $header = $peaces[0]; |
| 60 | + $payload = $peaces[1]; |
| 61 | + $signature = $peaces[2]; |
| 62 | + $hash = base64_encode(hash_hmac('sha256', "{$header}.{$payload}", $secret, true)); |
| 63 | + |
| 64 | + return hash_equals($signature, $hash); |
| 65 | + } |
| 66 | +} |
0 commit comments