JWT.php 23 KB

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