JWT.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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) floor($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) floor($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)) {
  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. if (!\is_resource($key) && !openssl_pkey_get_private($key)) {
  237. throw new DomainException('OpenSSL unable to validate key');
  238. }
  239. $success = \openssl_sign($msg, $signature, $key, $algorithm); // @phpstan-ignore-line
  240. if (!$success) {
  241. throw new DomainException('OpenSSL unable to sign data');
  242. }
  243. if ($alg === 'ES256' || $alg === 'ES256K') {
  244. $signature = self::signatureFromDER($signature, 256);
  245. } elseif ($alg === 'ES384') {
  246. $signature = self::signatureFromDER($signature, 384);
  247. }
  248. return $signature;
  249. case 'sodium_crypto':
  250. if (!\function_exists('sodium_crypto_sign_detached')) {
  251. throw new DomainException('libsodium is not available');
  252. }
  253. if (!\is_string($key)) {
  254. throw new InvalidArgumentException('key must be a string when using EdDSA');
  255. }
  256. try {
  257. // The last non-empty line is used as the key.
  258. $lines = array_filter(explode("\n", $key));
  259. $key = base64_decode((string) end($lines));
  260. if (\strlen($key) === 0) {
  261. throw new DomainException('Key cannot be empty string');
  262. }
  263. return sodium_crypto_sign_detached($msg, $key);
  264. } catch (Exception $e) {
  265. throw new DomainException($e->getMessage(), 0, $e);
  266. }
  267. }
  268. throw new DomainException('Algorithm not supported');
  269. }
  270. /**
  271. * Verify a signature with the message, key and method. Not all methods
  272. * are symmetric, so we must have a separate verify and sign method.
  273. *
  274. * @param string $msg The original message (header and body)
  275. * @param string $signature The original signature
  276. * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial For Ed*, ES*, HS*, a string key works. for RS*, must be an instance of OpenSSLAsymmetricKey
  277. * @param string $alg The algorithm
  278. *
  279. * @return bool
  280. *
  281. * @throws DomainException Invalid Algorithm, bad key, or OpenSSL failure
  282. */
  283. private static function verify(
  284. string $msg,
  285. string $signature,
  286. $keyMaterial,
  287. string $alg
  288. ): bool {
  289. if (empty(static::$supported_algs[$alg])) {
  290. throw new DomainException('Algorithm not supported');
  291. }
  292. list($function, $algorithm) = static::$supported_algs[$alg];
  293. switch ($function) {
  294. case 'openssl':
  295. $success = \openssl_verify($msg, $signature, $keyMaterial, $algorithm); // @phpstan-ignore-line
  296. if ($success === 1) {
  297. return true;
  298. }
  299. if ($success === 0) {
  300. return false;
  301. }
  302. // returns 1 on success, 0 on failure, -1 on error.
  303. throw new DomainException(
  304. 'OpenSSL error: ' . \openssl_error_string()
  305. );
  306. case 'sodium_crypto':
  307. if (!\function_exists('sodium_crypto_sign_verify_detached')) {
  308. throw new DomainException('libsodium is not available');
  309. }
  310. if (!\is_string($keyMaterial)) {
  311. throw new InvalidArgumentException('key must be a string when using EdDSA');
  312. }
  313. try {
  314. // The last non-empty line is used as the key.
  315. $lines = array_filter(explode("\n", $keyMaterial));
  316. $key = base64_decode((string) end($lines));
  317. if (\strlen($key) === 0) {
  318. throw new DomainException('Key cannot be empty string');
  319. }
  320. if (\strlen($signature) === 0) {
  321. throw new DomainException('Signature cannot be empty string');
  322. }
  323. return sodium_crypto_sign_verify_detached($signature, $msg, $key);
  324. } catch (Exception $e) {
  325. throw new DomainException($e->getMessage(), 0, $e);
  326. }
  327. case 'hash_hmac':
  328. default:
  329. if (!\is_string($keyMaterial)) {
  330. throw new InvalidArgumentException('key must be a string when using hmac');
  331. }
  332. $hash = \hash_hmac($algorithm, $msg, $keyMaterial, true);
  333. return self::constantTimeEquals($hash, $signature);
  334. }
  335. }
  336. /**
  337. * Decode a JSON string into a PHP object.
  338. *
  339. * @param string $input JSON string
  340. *
  341. * @return mixed The decoded JSON string
  342. *
  343. * @throws DomainException Provided string was invalid JSON
  344. */
  345. public static function jsonDecode(string $input)
  346. {
  347. $obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
  348. if ($errno = \json_last_error()) {
  349. self::handleJsonError($errno);
  350. } elseif ($obj === null && $input !== 'null') {
  351. throw new DomainException('Null result with non-null input');
  352. }
  353. return $obj;
  354. }
  355. /**
  356. * Encode a PHP array into a JSON string.
  357. *
  358. * @param array<mixed> $input A PHP array
  359. *
  360. * @return string JSON representation of the PHP array
  361. *
  362. * @throws DomainException Provided object could not be encoded to valid JSON
  363. */
  364. public static function jsonEncode(array $input): string
  365. {
  366. $json = \json_encode($input, \JSON_UNESCAPED_SLASHES);
  367. if ($errno = \json_last_error()) {
  368. self::handleJsonError($errno);
  369. } elseif ($json === 'null') {
  370. throw new DomainException('Null result with non-null input');
  371. }
  372. if ($json === false) {
  373. throw new DomainException('Provided object could not be encoded to valid JSON');
  374. }
  375. return $json;
  376. }
  377. /**
  378. * Decode a string with URL-safe Base64.
  379. *
  380. * @param string $input A Base64 encoded string
  381. *
  382. * @return string A decoded string
  383. *
  384. * @throws InvalidArgumentException invalid base64 characters
  385. */
  386. public static function urlsafeB64Decode(string $input): string
  387. {
  388. return \base64_decode(self::convertBase64UrlToBase64($input));
  389. }
  390. /**
  391. * Convert a string in the base64url (URL-safe Base64) encoding to standard base64.
  392. *
  393. * @param string $input A Base64 encoded string with URL-safe characters (-_ and no padding)
  394. *
  395. * @return string A Base64 encoded string with standard characters (+/) and padding (=), when
  396. * needed.
  397. *
  398. * @see https://www.rfc-editor.org/rfc/rfc4648
  399. */
  400. public static function convertBase64UrlToBase64(string $input): string
  401. {
  402. $remainder = \strlen($input) % 4;
  403. if ($remainder) {
  404. $padlen = 4 - $remainder;
  405. $input .= \str_repeat('=', $padlen);
  406. }
  407. return \strtr($input, '-_', '+/');
  408. }
  409. /**
  410. * Encode a string with URL-safe Base64.
  411. *
  412. * @param string $input The string you want encoded
  413. *
  414. * @return string The base64 encode of what you passed in
  415. */
  416. public static function urlsafeB64Encode(string $input): string
  417. {
  418. return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_'));
  419. }
  420. /**
  421. * Determine if an algorithm has been provided for each Key
  422. *
  423. * @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray
  424. * @param string|null $kid
  425. *
  426. * @throws UnexpectedValueException
  427. *
  428. * @return Key
  429. */
  430. private static function getKey(
  431. $keyOrKeyArray,
  432. ?string $kid
  433. ): Key {
  434. if ($keyOrKeyArray instanceof Key) {
  435. return $keyOrKeyArray;
  436. }
  437. if (empty($kid) && $kid !== '0') {
  438. throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
  439. }
  440. if ($keyOrKeyArray instanceof CachedKeySet) {
  441. // Skip "isset" check, as this will automatically refresh if not set
  442. return $keyOrKeyArray[$kid];
  443. }
  444. if (!isset($keyOrKeyArray[$kid])) {
  445. throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
  446. }
  447. return $keyOrKeyArray[$kid];
  448. }
  449. /**
  450. * @param string $left The string of known length to compare against
  451. * @param string $right The user-supplied string
  452. * @return bool
  453. */
  454. public static function constantTimeEquals(string $left, string $right): bool
  455. {
  456. if (\function_exists('hash_equals')) {
  457. return \hash_equals($left, $right);
  458. }
  459. $len = \min(self::safeStrlen($left), self::safeStrlen($right));
  460. $status = 0;
  461. for ($i = 0; $i < $len; $i++) {
  462. $status |= (\ord($left[$i]) ^ \ord($right[$i]));
  463. }
  464. $status |= (self::safeStrlen($left) ^ self::safeStrlen($right));
  465. return ($status === 0);
  466. }
  467. /**
  468. * Helper method to create a JSON error.
  469. *
  470. * @param int $errno An error number from json_last_error()
  471. *
  472. * @throws DomainException
  473. *
  474. * @return void
  475. */
  476. private static function handleJsonError(int $errno): void
  477. {
  478. $messages = [
  479. JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
  480. JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
  481. JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
  482. JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
  483. JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3
  484. ];
  485. throw new DomainException(
  486. isset($messages[$errno])
  487. ? $messages[$errno]
  488. : 'Unknown JSON error: ' . $errno
  489. );
  490. }
  491. /**
  492. * Get the number of bytes in cryptographic strings.
  493. *
  494. * @param string $str
  495. *
  496. * @return int
  497. */
  498. private static function safeStrlen(string $str): int
  499. {
  500. if (\function_exists('mb_strlen')) {
  501. return \mb_strlen($str, '8bit');
  502. }
  503. return \strlen($str);
  504. }
  505. /**
  506. * Convert an ECDSA signature to an ASN.1 DER sequence
  507. *
  508. * @param string $sig The ECDSA signature to convert
  509. * @return string The encoded DER object
  510. */
  511. private static function signatureToDER(string $sig): string
  512. {
  513. // Separate the signature into r-value and s-value
  514. $length = max(1, (int) (\strlen($sig) / 2));
  515. list($r, $s) = \str_split($sig, $length);
  516. // Trim leading zeros
  517. $r = \ltrim($r, "\x00");
  518. $s = \ltrim($s, "\x00");
  519. // Convert r-value and s-value from unsigned big-endian integers to
  520. // signed two's complement
  521. if (\ord($r[0]) > 0x7f) {
  522. $r = "\x00" . $r;
  523. }
  524. if (\ord($s[0]) > 0x7f) {
  525. $s = "\x00" . $s;
  526. }
  527. return self::encodeDER(
  528. self::ASN1_SEQUENCE,
  529. self::encodeDER(self::ASN1_INTEGER, $r) .
  530. self::encodeDER(self::ASN1_INTEGER, $s)
  531. );
  532. }
  533. /**
  534. * Encodes a value into a DER object.
  535. *
  536. * @param int $type DER tag
  537. * @param string $value the value to encode
  538. *
  539. * @return string the encoded object
  540. */
  541. private static function encodeDER(int $type, string $value): string
  542. {
  543. $tag_header = 0;
  544. if ($type === self::ASN1_SEQUENCE) {
  545. $tag_header |= 0x20;
  546. }
  547. // Type
  548. $der = \chr($tag_header | $type);
  549. // Length
  550. $der .= \chr(\strlen($value));
  551. return $der . $value;
  552. }
  553. /**
  554. * Encodes signature from a DER object.
  555. *
  556. * @param string $der binary signature in DER format
  557. * @param int $keySize the number of bits in the key
  558. *
  559. * @return string the signature
  560. */
  561. private static function signatureFromDER(string $der, int $keySize): string
  562. {
  563. // OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE
  564. list($offset, $_) = self::readDER($der);
  565. list($offset, $r) = self::readDER($der, $offset);
  566. list($offset, $s) = self::readDER($der, $offset);
  567. // Convert r-value and s-value from signed two's compliment to unsigned
  568. // big-endian integers
  569. $r = \ltrim($r, "\x00");
  570. $s = \ltrim($s, "\x00");
  571. // Pad out r and s so that they are $keySize bits long
  572. $r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT);
  573. $s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT);
  574. return $r . $s;
  575. }
  576. /**
  577. * Reads binary DER-encoded data and decodes into a single object
  578. *
  579. * @param string $der the binary data in DER format
  580. * @param int $offset the offset of the data stream containing the object
  581. * to decode
  582. *
  583. * @return array{int, string|null} the new offset and the decoded object
  584. */
  585. private static function readDER(string $der, int $offset = 0): array
  586. {
  587. $pos = $offset;
  588. $size = \strlen($der);
  589. $constructed = (\ord($der[$pos]) >> 5) & 0x01;
  590. $type = \ord($der[$pos++]) & 0x1f;
  591. // Length
  592. $len = \ord($der[$pos++]);
  593. if ($len & 0x80) {
  594. $n = $len & 0x1f;
  595. $len = 0;
  596. while ($n-- && $pos < $size) {
  597. $len = ($len << 8) | \ord($der[$pos++]);
  598. }
  599. }
  600. // Value
  601. if ($type === self::ASN1_BIT_STRING) {
  602. $pos++; // Skip the first contents octet (padding indicator)
  603. $data = \substr($der, $pos, $len - 1);
  604. $pos += $len - 1;
  605. } elseif (!$constructed) {
  606. $data = \substr($der, $pos, $len);
  607. $pos += $len;
  608. } else {
  609. $data = null;
  610. }
  611. return [$pos, $data];
  612. }
  613. }