PageRenderTime 25ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/twilio-php-master/Twilio/Jwt/JWT.php

https://bitbucket.org/OverSite/capstone-demo
PHP | 165 lines | 97 code | 12 blank | 56 comment | 19 complexity | e6d12303929e2249b7942aae30a76e38 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, MIT, LGPL-2.1, Apache-2.0
  1. <?php
  2. namespace Twilio\Jwt;
  3. /**
  4. * JSON Web Token implementation
  5. *
  6. * Minimum implementation used by Realtime auth, based on this spec:
  7. * http://self-issued.info/docs/draft-jones-json-web-token-01.html.
  8. *
  9. * @author Neuman Vong <neuman@twilio.com>
  10. */
  11. class JWT
  12. {
  13. /**
  14. * @param string $jwt The JWT
  15. * @param string|null $key The secret key
  16. * @param bool $verify Don't skip verification process
  17. * @return object The JWT's payload as a PHP object
  18. * @throws \DomainException
  19. * @throws \UnexpectedValueException
  20. */
  21. public static function decode($jwt, $key = null, $verify = true)
  22. {
  23. $tks = explode('.', $jwt);
  24. if (count($tks) != 3) {
  25. throw new \UnexpectedValueException('Wrong number of segments');
  26. }
  27. list($headb64, $payloadb64, $cryptob64) = $tks;
  28. if (null === ($header = self::jsonDecode(self::urlsafeB64Decode($headb64)))
  29. ) {
  30. throw new \UnexpectedValueException('Invalid segment encoding');
  31. }
  32. if (null === $payload = self::jsonDecode(self::urlsafeB64Decode($payloadb64))
  33. ) {
  34. throw new \UnexpectedValueException('Invalid segment encoding');
  35. }
  36. $sig = self::urlsafeB64Decode($cryptob64);
  37. if ($verify) {
  38. if (empty($header->alg)) {
  39. throw new \DomainException('Empty algorithm');
  40. }
  41. if ($sig != self::sign("$headb64.$payloadb64", $key, $header->alg)) {
  42. throw new \UnexpectedValueException('Signature verification failed');
  43. }
  44. }
  45. return $payload;
  46. }
  47. /**
  48. * @param object|array $payload PHP object or array
  49. * @param string $key The secret key
  50. * @param string $algo The signing algorithm
  51. * @param array $additionalHeaders Additional keys/values to add to the header
  52. *
  53. * @return string A JWT
  54. */
  55. public static function encode($payload, $key, $algo = 'HS256', $additionalHeaders = array())
  56. {
  57. $header = array('typ' => 'JWT', 'alg' => $algo);
  58. $header = $header + $additionalHeaders;
  59. $segments = array();
  60. $segments[] = self::urlsafeB64Encode(self::jsonEncode($header));
  61. $segments[] = self::urlsafeB64Encode(self::jsonEncode($payload));
  62. $signing_input = implode('.', $segments);
  63. $signature = self::sign($signing_input, $key, $algo);
  64. $segments[] = self::urlsafeB64Encode($signature);
  65. return implode('.', $segments);
  66. }
  67. /**
  68. * @param string $msg The message to sign
  69. * @param string $key The secret key
  70. * @param string $method The signing algorithm
  71. * @return string An encrypted message
  72. * @throws \DomainException
  73. */
  74. public static function sign($msg, $key, $method = 'HS256')
  75. {
  76. $methods = array(
  77. 'HS256' => 'sha256',
  78. 'HS384' => 'sha384',
  79. 'HS512' => 'sha512',
  80. );
  81. if (empty($methods[$method])) {
  82. throw new \DomainException('Algorithm not supported');
  83. }
  84. return hash_hmac($methods[$method], $msg, $key, true);
  85. }
  86. /**
  87. * @param string $input JSON string
  88. * @return object Object representation of JSON string
  89. * @throws \DomainException
  90. */
  91. public static function jsonDecode($input)
  92. {
  93. $obj = json_decode($input);
  94. if (function_exists('json_last_error') && $errno = json_last_error()) {
  95. self::handleJsonError($errno);
  96. } else if ($obj === null && $input !== 'null') {
  97. throw new \DomainException('Null result with non-null input');
  98. }
  99. return $obj;
  100. }
  101. /**
  102. * @param object|array $input A PHP object or array
  103. * @return string JSON representation of the PHP object or array
  104. * @throws \DomainException
  105. */
  106. public static function jsonEncode($input)
  107. {
  108. $json = json_encode($input);
  109. if (function_exists('json_last_error') && $errno = json_last_error()) {
  110. self::handleJsonError($errno);
  111. } else if ($json === 'null' && $input !== null) {
  112. throw new \DomainException('Null result with non-null input');
  113. }
  114. return $json;
  115. }
  116. /**
  117. * @param string $input A base64 encoded string
  118. *
  119. * @return string A decoded string
  120. */
  121. public static function urlsafeB64Decode($input)
  122. {
  123. $padlen = 4 - strlen($input) % 4;
  124. $input .= str_repeat('=', $padlen);
  125. return base64_decode(strtr($input, '-_', '+/'));
  126. }
  127. /**
  128. * @param string $input Anything really
  129. *
  130. * @return string The base64 encode of what you passed in
  131. */
  132. public static function urlsafeB64Encode($input)
  133. {
  134. return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
  135. }
  136. /**
  137. * @param int $errno An error number from json_last_error()
  138. *
  139. * @throws \DomainException
  140. */
  141. private static function handleJsonError($errno)
  142. {
  143. $messages = array(
  144. JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
  145. JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
  146. JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
  147. );
  148. throw new \DomainException(isset($messages[$errno])
  149. ? $messages[$errno]
  150. : 'Unknown JSON error: ' . $errno
  151. );
  152. }
  153. }