JWToken.class.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /**
  3. * JWToken utilities.
  4. * @author Kiss Team
  5. * @category Plugin
  6. * @license MIT
  7. */
  8. class JWToken {
  9. /* Décrypte une JWT Token avec la clé secrete fournie
  10. */
  11. public static function parse($encodedString,$key){
  12. $infos = explode('.', $encodedString);
  13. if(count($infos)!=3) throw new Exception("JWT error : incorrect format", 401);
  14. list($header64, $payloadb64, $signatureb64) = $infos;
  15. $header = $header64;
  16. $payload = $payloadb64;
  17. //header
  18. $remainder = strlen($header) % 4;
  19. if ($remainder) {
  20. $padlen = 4 - $remainder;
  21. $header .= str_repeat('=', $padlen);
  22. }
  23. $header = base64_decode(strtr($header, '-_', '+/'));
  24. $header = json_decode($header,true);
  25. //payload
  26. $remainder = strlen($payload) % 4;
  27. if ($remainder) {
  28. $padlen = 4 - $remainder;
  29. $payload .= str_repeat('=', $padlen);
  30. }
  31. $payload = base64_decode(strtr($payload, '-_', '+/'));
  32. $payload = json_decode($payload,true);
  33. //signature
  34. $remainder = strlen($signatureb64) % 4;
  35. if ($remainder) {
  36. $padlen = 4 - $remainder;
  37. $signatureb64 .= str_repeat('=', $padlen);
  38. }
  39. $signature = base64_decode(strtr($signatureb64, '-_', '+/'));
  40. $hash = hash_hmac('SHA256', "$header64.$payloadb64", $key, true);
  41. $len = min(mb_strlen($signature, '8bit'),mb_strlen($hash, '8bit') );
  42. $status = 0;
  43. for ($i = 0; $i < $len; $i++) {
  44. $status |= (ord($signature[$i]) ^ ord($hash[$i]));
  45. }
  46. $status |= (mb_strlen($signature, '8bit') ^ mb_strlen($hash, '8bit'));
  47. $verify = ($status === 0);
  48. if(!$verify) throw new Exception("JWT error : bad signature or encryption key", 401);
  49. if($payload['exp']<time()) throw new Exception("JWT error : token is expired since ".date('d/m/Y H:i:s',$payload['exp']), 498);
  50. return $payload;
  51. }
  52. //Créé un token crypté en HS256 à partir du payload / clé privée fournis
  53. public static function createFromJson($payload, $key)
  54. {
  55. $header = json_encode(array('typ' => 'JWT', 'alg' => 'HS256'));
  56. $payload = json_encode($payload);
  57. $segments = array();
  58. $segments[] = str_replace('=', '', strtr(base64_encode($header), '+/', '-_'));
  59. $segments[] = str_replace('=', '', strtr(base64_encode($payload), '+/', '-_'));
  60. $signing_input = implode('.', $segments);
  61. $signature = hash_hmac('SHA256', $signing_input, $key, true);
  62. $segments[] = str_replace('=', '', strtr(base64_encode($signature), '+/', '-_'));
  63. return implode('.', $segments);
  64. }
  65. }
  66. ?>