JWT.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. <?php
  2. namespace Firebase\JWT;
  3. use ArrayAccess;
  4. use DateTime;
  5. use DomainException;
  6. use Exception;
  7. use InvalidArgumentException;
  8. use OpenSSLAsymmetricKey;
  9. use OpenSSLCertificate;
  10. use stdClass;
  11. use UnexpectedValueException;
  12. /**
  13. * JSON Web Token implementation, based on this spec:
  14. * https://tools.ietf.org/html/rfc7519
  15. *
  16. * PHP version 5
  17. *
  18. * @category Authentication
  19. * @package Authentication_JWT
  20. * @author Neuman Vong <neuman@twilio.com>
  21. * @author Anant Narayanan <anant@php.net>
  22. * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
  23. * @link https://github.com/firebase/php-jwt
  24. */
  25. class JWT
  26. {
  27. private const ASN1_INTEGER = 0x02;
  28. private const ASN1_SEQUENCE = 0x10;
  29. private const ASN1_BIT_STRING = 0x03;
  30. /**
  31. * When checking nbf, iat or expiration times,
  32. * we want to provide some extra leeway time to
  33. * account for clock skew.
  34. *
  35. * @var int
  36. */
  37. public static $leeway = 0;
  38. /**
  39. * Allow the current timestamp to be specified.
  40. * Useful for fixing a value within unit testing.
  41. * Will default to PHP time() value if null.
  42. *
  43. * @var ?int
  44. */
  45. public static $timestamp = null;
  46. /**
  47. * @var array<string, string[]>
  48. */
  49. public static $supported_algs = [
  50. 'ES384' => ['openssl', 'SHA384'],
  51. 'ES256' => ['openssl', 'SHA256'],
  52. 'ES256K' => ['openssl', 'SHA256'],
  53. 'HS256' => ['hash_hmac', 'SHA256'],
  54. 'HS384' => ['hash_hmac', 'SHA384'],
  55. 'HS512' => ['hash_hmac', 'SHA512'],
  56. 'RS256' => ['openssl', 'SHA256'],
  57. 'RS384' => ['openssl', 'SHA384'],
  58. 'RS512' => ['openssl', 'SHA512'],
  59. 'EdDSA' => ['sodium_crypto', 'EdDSA'],
  60. ];
  61. /**
  62. * Decodes a JWT string into a PHP object.
  63. *
  64. * @param string $jwt The JWT
  65. * @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray The Key or associative array of key IDs
  66. * (kid) to Key objects.
  67. * If the algorithm used is asymmetric, this is
  68. * the public key.
  69. * Each Key object contains an algorithm and
  70. * matching key.
  71. * Supported algorithms are 'ES384','ES256',
  72. * 'HS256', 'HS384', 'HS512', 'RS256', 'RS384'
  73. * and 'RS512'.
  74. * @param stdClass $headers Optional. Populates stdClass with headers.
  75. *
  76. * @return stdClass The JWT's payload as a PHP object
  77. *
  78. * @throws InvalidArgumentException Provided key/key-array was empty or malformed
  79. * @throws DomainException Provided JWT is malformed
  80. * @throws UnexpectedValueException Provided JWT was invalid
  81. * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
  82. * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
  83. * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
  84. * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
  85. *
  86. * @uses jsonDecode
  87. * @uses urlsafeB64Decode
  88. */
  89. public static function decode(
  90. string $jwt,
  91. $keyOrKeyArray,
  92. stdClass &$headers = null
  93. ): stdClass {
  94. // Validate JWT
  95. $timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp;
  96. if (empty($keyOrKeyArray)) {
  97. throw new InvalidArgumentException('Key may not be empty');
  98. }
  99. $tks = \explode('.', $jwt);
  100. if (\count($tks) !== 3) {
  101. throw new UnexpectedValueException('Wrong number of segments');
  102. }
  103. list($headb64, $bodyb64, $cryptob64) = $tks;
  104. $headerRaw = static::urlsafeB64Decode($headb64);
  105. if (null === ($header = static::jsonDecode($headerRaw))) {
  106. throw new UnexpectedValueException('Invalid header encoding');
  107. }
  108. if ($headers !== null) {
  109. $headers = $header;
  110. }
  111. $payloadRaw = static::urlsafeB64Decode($bodyb64);
  112. if (null === ($payload = static::jsonDecode($payloadRaw))) {
  113. throw new UnexpectedValueException('Invalid claims encoding');
  114. }
  115. if (\is_array($payload)) {
  116. // prevent PHP Fatal Error in edge-cases when payload is empty array
  117. $payload = (object) $payload;
  118. }
  119. if (!$payload instanceof stdClass) {
  120. throw new UnexpectedValueException('Payload must be a JSON object');
  121. }
  122. $sig = static::urlsafeB64Decode($cryptob64);
  123. if (empty($header->alg)) {
  124. throw new UnexpectedValueException('Empty algorithm');
  125. }
  126. if (empty(static::$supported_algs[$header->alg])) {
  127. throw new UnexpectedValueException('Algorithm not supported');
  128. }
  129. $key = self::getKey($keyOrKeyArray, property_exists($header, 'kid') ? $header->kid : null);
  130. // Check the algorithm
  131. if (!self::constantTimeEquals($key->getAlgorithm(), $header->alg)) {
  132. // See issue #351
  133. throw new UnexpectedValueException('Incorrect key for this algorithm');
  134. }
  135. if (\in_array($header->alg, ['ES256', 'ES256K', 'ES384'], true)) {
  136. // OpenSSL expects an ASN.1 DER sequence for ES256/ES256K/ES384 signatures
  137. $sig = self::signatureToDER($sig);
  138. }
  139. if (!self::verify("{$headb64}.{$bodyb64}", $sig, $key->getKeyMaterial(), $header->alg)) {
  140. throw new SignatureInvalidException('Signature verification failed');
  141. }
  142. // Check the nbf if it is defined. This is the time that the
  143. // token can actually be used. If it's not yet that time, abort.
  144. if (isset($payload->nbf) && floor($payload->nbf) > ($timestamp + static::$leeway)) {
  145. $ex = new BeforeValidException(
  146. 'Cannot handle token with nbf prior to ' . \date(DateTime::ISO8601, (int) $payload->nbf)
  147. );
  148. $ex->setPayload($payload);
  149. throw $ex;
  150. }
  151. // Check that this token has been created before 'now'. This prevents
  152. // using tokens that have been created for later use (and haven't
  153. // correctly used the nbf claim).
  154. if (!isset($payload->nbf) && isset($payload->iat) && floor($payload->iat) > ($timestamp + static::$leeway)) {
  155. $ex = new BeforeValidException(
  156. 'Cannot handle token with iat prior to ' . \date(DateTime::ISO8601, (int) $payload->iat)
  157. );
  158. $ex->setPayload($payload);
  159. throw $ex;
  160. }
  161. // Check if this token has expired.
  162. if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
  163. $ex = new ExpiredException('Expired token');
  164. $ex->setPayload($payload);
  165. throw $ex;
  166. }
  167. return $payload;
  168. }
  169. /**
  170. * Converts and signs a PHP array into a JWT string.
  171. *
  172. * @param array<mixed> $payload PHP array
  173. * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
  174. * @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256',
  175. * 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
  176. * @param string $keyId
  177. * @param array<string, string> $head An array with header elements to attach
  178. *
  179. * @return string A signed JWT
  180. *
  181. * @uses jsonEncode
  182. * @uses urlsafeB64Encode
  183. */
  184. public static function encode(
  185. array $payload,
  186. $key,
  187. string $alg,
  188. string $keyId = null,
  189. array $head = null
  190. ): string {
  191. $header = ['typ' => 'JWT'];
  192. if (isset($head) && \is_array($head)) {
  193. $header = \array_merge($header, $head);
  194. }
  195. $header['alg'] = $alg;
  196. if ($keyId !== null) {
  197. $header['kid'] = $keyId;
  198. }
  199. $segments = [];
  200. $segments[] = static::urlsafeB64Encode((string) static::jsonEncode($header));
  201. $segments[] = static::urlsafeB64Encode((string) static::jsonEncode($payload));
  202. $signing_input = \implode('.', $segments);
  203. $signature = static::sign($signing_input, $key, $alg);
  204. $segments[] = static::urlsafeB64Encode($signature);
  205. return \implode('.', $segments);
  206. }
  207. /**
  208. * Sign a string with a given key and algorithm.
  209. *
  210. * @param string $msg The message to sign
  211. * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
  212. * @param string $alg Supported algorithms are 'EdDSA', 'ES384', 'ES256', 'ES256K', 'HS256',
  213. * 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
  214. *
  215. * @return string An encrypted message
  216. *
  217. * @throws DomainException Unsupported algorithm or bad key was specified
  218. */
  219. public static function sign(
  220. string $msg,
  221. $key,
  222. string $alg
  223. ): string {
  224. if (empty(static::$supported_algs[$alg])) {
  225. throw new DomainException('Algorithm not supported');
  226. }
  227. list($function, $algorithm) = static::$supported_algs[$alg];
  228. switch ($function) {
  229. case 'hash_hmac':
  230. if (!\is_string($key)) {
  231. throw new InvalidArgumentException('key must be a string when using hmac');
  232. }
  233. return \hash_hmac($algorithm, $msg, $key, true);
  234. case 'openssl':
  235. $signature = '';
  236. $success = \openssl_sign($msg, $signature, $key, $algorithm); // @phpstan-ignore-line
  237. if (!$success) {
  238. throw new DomainException('OpenSSL unable to sign data');
  239. }
  240. if ($alg === 'ES256' || $alg === 'ES256K') {
  241. $signature = self::signatureFromDER($signature, 256);
  242. } elseif ($alg === 'ES384') {
  243. $signature = self::signatureFromDER($signature, 384);
  244. }
  245. return $signature;
  246. case 'sodium_crypto':
  247. if (!\function_exists('sodium_crypto_sign_detached')) {
  248. throw new DomainException('libsodium is not available');
  249. }
  250. if (!\is_string($key)) {
  251. throw new InvalidArgumentException('key must be a string when using EdDSA');
  252. }
  253. try {
  254. // The last non-empty line is used as the key.
  255. $lines = array_filter(explode("\n", $key));
  256. $key = base64_decode((string) end($lines));
  257. if (\strlen($key) === 0) {
  258. throw new DomainException('Key cannot be empty string');
  259. }
  260. return sodium_crypto_sign_detached($msg, $key);
  261. } catch (Exception $e) {
  262. throw new DomainException($e->getMessage(), 0, $e);
  263. }
  264. }
  265. throw new DomainException('Algorithm not supported');
  266. }
  267. /**
  268. * Verify a signature with the message, key and method. Not all methods
  269. * are symmetric, so we must have a separate verify and sign method.
  270. *
  271. * @param string $msg The original message (header and body)
  272. * @param string $signature The original signature
  273. * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial For Ed*, ES*, HS*, a string key works. for RS*, must be an instance of OpenSSLAsymmetricKey
  274. * @param string $alg The algorithm
  275. *
  276. * @return bool
  277. *
  278. * @throws DomainException Invalid Algorithm, bad key, or OpenSSL failure
  279. */
  280. private static function verify(
  281. string $msg,
  282. string $signature,
  283. $keyMaterial,
  284. string $alg
  285. ): bool {
  286. if (empty(static::$supported_algs[$alg])) {
  287. throw new DomainException('Algorithm not supported');
  288. }
  289. list($function, $algorithm) = static::$supported_algs[$alg];
  290. switch ($function) {
  291. case 'openssl':
  292. $success = \openssl_verify($msg, $signature, $keyMaterial, $algorithm); // @phpstan-ignore-line
  293. if ($success === 1) {
  294. return true;
  295. }
  296. if ($success === 0) {
  297. return false;
  298. }
  299. // returns 1 on success, 0 on failure, -1 on error.
  300. throw new DomainException(
  301. 'OpenSSL error: ' . \openssl_error_string()
  302. );
  303. case 'sodium_crypto':
  304. if (!\function_exists('sodium_crypto_sign_verify_detached')) {
  305. throw new DomainException('libsodium is not available');
  306. }
  307. if (!\is_string($keyMaterial)) {
  308. throw new InvalidArgumentException('key must be a string when using EdDSA');
  309. }
  310. try {
  311. // The last non-empty line is used as the key.
  312. $lines = array_filter(explode("\n", $keyMaterial));
  313. $key = base64_decode((string) end($lines));
  314. if (\strlen($key) === 0) {
  315. throw new DomainException('Key cannot be empty string');
  316. }
  317. if (\strlen($signature) === 0) {
  318. throw new DomainException('Signature cannot be empty string');
  319. }
  320. return sodium_crypto_sign_verify_detached($signature, $msg, $key);
  321. } catch (Exception $e) {
  322. throw new DomainException($e->getMessage(), 0, $e);
  323. }
  324. case 'hash_hmac':
  325. default:
  326. if (!\is_string($keyMaterial)) {
  327. throw new InvalidArgumentException('key must be a string when using hmac');
  328. }
  329. $hash = \hash_hmac($algorithm, $msg, $keyMaterial, true);
  330. return self::constantTimeEquals($hash, $signature);
  331. }
  332. }
  333. /**
  334. * Decode a JSON string into a PHP object.
  335. *
  336. * @param string $input JSON string
  337. *
  338. * @return mixed The decoded JSON string
  339. *
  340. * @throws DomainException Provided string was invalid JSON
  341. */
  342. public static function jsonDecode(string $input)
  343. {
  344. $obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
  345. if ($errno = \json_last_error()) {
  346. self::handleJsonError($errno);
  347. } elseif ($obj === null && $input !== 'null') {
  348. throw new DomainException('Null result with non-null input');
  349. }
  350. return $obj;
  351. }
  352. /**
  353. * Encode a PHP array into a JSON string.
  354. *
  355. * @param array<mixed> $input A PHP array
  356. *
  357. * @return string JSON representation of the PHP array
  358. *
  359. * @throws DomainException Provided object could not be encoded to valid JSON
  360. */
  361. public static function jsonEncode(array $input): string
  362. {
  363. if (PHP_VERSION_ID >= 50400) {
  364. $json = \json_encode($input, \JSON_UNESCAPED_SLASHES);
  365. } else {
  366. // PHP 5.3 only
  367. $json = \json_encode($input);
  368. }
  369. if ($errno = \json_last_error()) {
  370. self::handleJsonError($errno);
  371. } elseif ($json === 'null') {
  372. throw new DomainException('Null result with non-null input');
  373. }
  374. if ($json === false) {
  375. throw new DomainException('Provided object could not be encoded to valid JSON');
  376. }
  377. return $json;
  378. }
  379. /**
  380. * Decode a string with URL-safe Base64.
  381. *
  382. * @param string $input A Base64 encoded string
  383. *
  384. * @return string A decoded string
  385. *
  386. * @throws InvalidArgumentException invalid base64 characters
  387. */
  388. public static function urlsafeB64Decode(string $input): string
  389. {
  390. return \base64_decode(self::convertBase64UrlToBase64($input));
  391. }
  392. /**
  393. * Convert a string in the base64url (URL-safe Base64) encoding to standard base64.
  394. *
  395. * @param string $input A Base64 encoded string with URL-safe characters (-_ and no padding)
  396. *
  397. * @return string A Base64 encoded string with standard characters (+/) and padding (=), when
  398. * needed.
  399. *
  400. * @see https://www.rfc-editor.org/rfc/rfc4648
  401. */
  402. public static function convertBase64UrlToBase64(string $input): string
  403. {
  404. $remainder = \strlen($input) % 4;
  405. if ($remainder) {
  406. $padlen = 4 - $remainder;
  407. $input .= \str_repeat('=', $padlen);
  408. }
  409. return \strtr($input, '-_', '+/');
  410. }
  411. /**
  412. * Encode a string with URL-safe Base64.
  413. *
  414. * @param string $input The string you want encoded
  415. *
  416. * @return string The base64 encode of what you passed in
  417. */
  418. public static function urlsafeB64Encode(string $input): string
  419. {
  420. return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_'));
  421. }
  422. /**
  423. * Determine if an algorithm has been provided for each Key
  424. *
  425. * @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray
  426. * @param string|null $kid
  427. *
  428. * @throws UnexpectedValueException
  429. *
  430. * @return Key
  431. */
  432. private static function getKey(
  433. $keyOrKeyArray,
  434. ?string $kid
  435. ): Key {
  436. if ($keyOrKeyArray instanceof Key) {
  437. return $keyOrKeyArray;
  438. }
  439. if (empty($kid) && $kid !== '0') {
  440. throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
  441. }
  442. if ($keyOrKeyArray instanceof CachedKeySet) {
  443. // Skip "isset" check, as this will automatically refresh if not set
  444. return $keyOrKeyArray[$kid];
  445. }
  446. if (!isset($keyOrKeyArray[$kid])) {
  447. throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
  448. }
  449. return $keyOrKeyArray[$kid];
  450. }
  451. /**
  452. * @param string $left The string of known length to compare against
  453. * @param string $right The user-supplied string
  454. * @return bool
  455. */
  456. public static function constantTimeEquals(string $left, string $right): bool
  457. {
  458. if (\function_exists('hash_equals')) {
  459. return \hash_equals($left, $right);
  460. }
  461. $len = \min(self::safeStrlen($left), self::safeStrlen($right));
  462. $status = 0;
  463. for ($i = 0; $i < $len; $i++) {
  464. $status |= (\ord($left[$i]) ^ \ord($right[$i]));
  465. }
  466. $status |= (self::safeStrlen($left) ^ self::safeStrlen($right));
  467. return ($status === 0);
  468. }
  469. /**
  470. * Helper method to create a JSON error.
  471. *
  472. * @param int $errno An error number from json_last_error()
  473. *
  474. * @throws DomainException
  475. *
  476. * @return void
  477. */
  478. private static function handleJsonError(int $errno): void
  479. {
  480. $messages = [
  481. JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
  482. JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
  483. JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
  484. JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
  485. JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3
  486. ];
  487. throw new DomainException(
  488. isset($messages[$errno])
  489. ? $messages[$errno]
  490. : 'Unknown JSON error: ' . $errno
  491. );
  492. }
  493. /**
  494. * Get the number of bytes in cryptographic strings.
  495. *
  496. * @param string $str
  497. *
  498. * @return int
  499. */
  500. private static function safeStrlen(string $str): int
  501. {
  502. if (\function_exists('mb_strlen')) {
  503. return \mb_strlen($str, '8bit');
  504. }
  505. return \strlen($str);
  506. }
  507. /**
  508. * Convert an ECDSA signature to an ASN.1 DER sequence
  509. *
  510. * @param string $sig The ECDSA signature to convert
  511. * @return string The encoded DER object
  512. */
  513. private static function signatureToDER(string $sig): string
  514. {
  515. // Separate the signature into r-value and s-value
  516. $length = max(1, (int) (\strlen($sig) / 2));
  517. list($r, $s) = \str_split($sig, $length);
  518. // Trim leading zeros
  519. $r = \ltrim($r, "\x00");
  520. $s = \ltrim($s, "\x00");
  521. // Convert r-value and s-value from unsigned big-endian integers to
  522. // signed two's complement
  523. if (\ord($r[0]) > 0x7f) {
  524. $r = "\x00" . $r;
  525. }
  526. if (\ord($s[0]) > 0x7f) {
  527. $s = "\x00" . $s;
  528. }
  529. return self::encodeDER(
  530. self::ASN1_SEQUENCE,
  531. self::encodeDER(self::ASN1_INTEGER, $r) .
  532. self::encodeDER(self::ASN1_INTEGER, $s)
  533. );
  534. }
  535. /**
  536. * Encodes a value into a DER object.
  537. *
  538. * @param int $type DER tag
  539. * @param string $value the value to encode
  540. *
  541. * @return string the encoded object
  542. */
  543. private static function encodeDER(int $type, string $value): string
  544. {
  545. $tag_header = 0;
  546. if ($type === self::ASN1_SEQUENCE) {
  547. $tag_header |= 0x20;
  548. }
  549. // Type
  550. $der = \chr($tag_header | $type);
  551. // Length
  552. $der .= \chr(\strlen($value));
  553. return $der . $value;
  554. }
  555. /**
  556. * Encodes signature from a DER object.
  557. *
  558. * @param string $der binary signature in DER format
  559. * @param int $keySize the number of bits in the key
  560. *
  561. * @return string the signature
  562. */
  563. private static function signatureFromDER(string $der, int $keySize): string
  564. {
  565. // OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE
  566. list($offset, $_) = self::readDER($der);
  567. list($offset, $r) = self::readDER($der, $offset);
  568. list($offset, $s) = self::readDER($der, $offset);
  569. // Convert r-value and s-value from signed two's compliment to unsigned
  570. // big-endian integers
  571. $r = \ltrim($r, "\x00");
  572. $s = \ltrim($s, "\x00");
  573. // Pad out r and s so that they are $keySize bits long
  574. $r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT);
  575. $s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT);
  576. return $r . $s;
  577. }
  578. /**
  579. * Reads binary DER-encoded data and decodes into a single object
  580. *
  581. * @param string $der the binary data in DER format
  582. * @param int $offset the offset of the data stream containing the object
  583. * to decode
  584. *
  585. * @return array{int, string|null} the new offset and the decoded object
  586. */
  587. private static function readDER(string $der, int $offset = 0): array
  588. {
  589. $pos = $offset;
  590. $size = \strlen($der);
  591. $constructed = (\ord($der[$pos]) >> 5) & 0x01;
  592. $type = \ord($der[$pos++]) & 0x1f;
  593. // Length
  594. $len = \ord($der[$pos++]);
  595. if ($len & 0x80) {
  596. $n = $len & 0x1f;
  597. $len = 0;
  598. while ($n-- && $pos < $size) {
  599. $len = ($len << 8) | \ord($der[$pos++]);
  600. }
  601. }
  602. // Value
  603. if ($type === self::ASN1_BIT_STRING) {
  604. $pos++; // Skip the first contents octet (padding indicator)
  605. $data = \substr($der, $pos, $len - 1);
  606. $pos += $len - 1;
  607. } elseif (!$constructed) {
  608. $data = \substr($der, $pos, $len);
  609. $pos += $len;
  610. } else {
  611. $data = null;
  612. }
  613. return [$pos, $data];
  614. }
  615. }