This method will try to load and decrypt the given token using a JWKSet.
If succeeded, the methods will populate the $recipient variable and returns the JWE.

@throws \Exception
962760
public function loadAndDecryptWithKeySet(string $token, JWKSet $keyset, ?int &$recipient): JWE
    {
        try {
            $jwe = $this->serializerManager->unserialize($token);
            $nbRecipients = $jwe->countRecipients();
            for ($i = 0; $i < $nbRecipients; ++$i) {
                if ($this->processRecipient($jwe, $keyset, $i)) {
                    $recipient = $i;

                    return $jwe;
                }
            }
        } catch (\Exception $e) {
            // Nothing to do. Exception thrown just after
        }

        throw new \Exception('Unable to load and decrypt the token.');
    }
440332
public function verify($credentials)
    {
        if(!array_key_exists("jwt", $credentials) || empty($credentials["jwt"])) {
            throw new \Exception("JWT is required");
        }

        // Make sure we have a secret key to decode the JWT
        if(!array_key_exists("secret_key", $credentials) || empty($credentials["secret_key"])) {
            throw new \Exception("Secret Key is required to decode this JWT");
        }

        // Get hash alg from params, default to HS256
        $hashAlgs = array("HS256");
        if(array_key_exists("hash_alg", $credentials) && !empty($credentials["hash_alg"])) {
            $hashAlgs[] = $credentials["hash_alg"];
            $hashAlgs = array_unique($hashAlgs);
        }

        $token = JWT::decode($credentials["jwt"], $credentials["secret_key"], $hashAlgs);

        // User ID is a good checksum to make sure we have a valid JWT
        if(empty($token) || empty($token->id)) {
            throw new \Exception("JWT Token invalid");
        }

        return $token;
    }
210329
def unpack(self, token):
        
        if not token:
            raise KeyError

        _jwe_header = _jws_header = None

        # Check if it's an encrypted JWT
        darg = {}
        if self.allowed_enc_encs:
            darg['enc'] = self.allowed_enc_encs
        if self.allowed_enc_algs:
            darg['alg'] = self.allowed_enc_algs
        try:
            _decryptor = jwe_factory(token, **darg)
        except (KeyError, HeaderError):
            _decryptor = None

        if _decryptor:
            # Yes, try to decode
            _info = self._decrypt(_decryptor, token)
            _jwe_header = _decryptor.jwt.headers
            # Try to find out if the information encrypted was a signed JWT
            try:
                _content_type = _decryptor.jwt.headers['cty']
            except KeyError:
                _content_type = ''
        else:
            _content_type = 'jwt'
            _info = token

        # If I have reason to believe the information I have is a signed JWT
        if _content_type.lower() == 'jwt':
            # Check that is a signed JWT
            if self.allowed_sign_algs:
                _verifier = jws_factory(_info, alg=self.allowed_sign_algs)
            else:
                _verifier = jws_factory(_info)

            if _verifier:
                _info = self._verify(_verifier, _info)
            else:
                raise Exception()
            _jws_header = _verifier.jwt.headers
        else:
            # So, not a signed JWT
            try:
                # A JSON document ?
                _info = json.loads(_info)
            except JSONDecodeError:  # Oh, no ! Not JSON
                return _info
            except TypeError:
                try:
                    _info = as_unicode(_info)
                    _info = json.loads(_info)
                except JSONDecodeError:  # Oh, no ! Not JSON
                    return _info

        # If I know what message class the info should be mapped into
        if self.msg_cls:
            _msg_cls = self.msg_cls
        else:
            try:
                # try to find a issuer specific message class
                _msg_cls = self.iss2msg_cls[_info['iss']]
            except KeyError:
                _msg_cls = None

        if _msg_cls:
            vp_args = {'skew': self.skew}
            if self.iss:
                vp_args['aud'] = self.iss
            _info = self.verify_profile(_msg_cls, _info, **vp_args)
            _info.jwe_header = _jwe_header
            _info.jws_header = _jws_header
            return _info
        else:
            return _info
102193
public function decryptUsingKeySet(JWE &$jwe, JWKSet $jwkset, int $recipient): bool
    {
        $this->checkJWKSet($jwkset);
        $this->checkPayload($jwe);
        $this->checkRecipients($jwe);

        $plaintext = $this->decryptRecipientKey($jwe, $jwkset, $recipient);
        if (null !== $plaintext) {
            $jwe = $jwe->withPayload($plaintext);

            return true;
        }

        return false;
    }
658
public function decryptUsingKey(JWE &$jwe, JWK $jwk, int $recipient): bool
    {
        $jwkset = new JWKSet([$jwk]);

        return $this->decryptUsingKeySet($jwe, $jwkset, $recipient);
    }
527069
private function decodeToken($jwt)
    {
        // Decode the token.
        $decodedToken = \JWT::decode($jwt, $this->secret, ['HS256']);

        // Validate that this JWT was made for us.
        $aud = property_exists($decodedToken, 'aud') ? $decodedToken->aud : null;
        if ($aud !== $this->localId) {
            throw new \UnexpectedValueException('This token is not intended for us.');
        }

        return $decodedToken;
    }
1091196
public function getJWT()
	{
		if($this->personalKeyPair === NULL)
			throw new \Exception("JWT cannot be built without the personalKey");
		
		// create and sign JWT
		$signer = new Sha512();
		
		$personalPrivateKey = PrivateKey::formatPEM($this->personalKeyPair->getPrivateKey());
		
		$token = (new Builder())
			->set('socialRecord', base64_encode($this->socialRecord->getJSONString()))
			->sign($signer, $personalPrivateKey)
			->getToken();
		
		return $token->__toString();
	}
221672
public function loadFromUrl(string $url, array $header = []): JWKSet
    {
        $content = $this->getContent($url, $header);
        $data = $this->jsonConverter->decode($content);
        if (!\is_array($data)) {
            throw new \RuntimeException('Invalid content.');
        }

        return JWKSet::createFromKeyData($data);
    }
942905
public function decrypt($message)
    {
        $authKey = $this->authen($this->password);
        $data    = \base64_decode($message, true);

        if ($data === false)
        {
            throw new Exceptions\Runtime('IV generation failed');
        }

        $hash = \hash(self::ALGORITHM, '', true);

        $hs  = \mb_strlen($hash, '8bit');
        $mac = \mb_substr($data, 0, $hs, '8bit');

        $cipherText = \mb_substr($data, $hs, null, '8bit');

        $calculated = \hash_hmac(
            self::ALGORITHM,
            $cipherText,
            $authKey,
            true
        );

        if (!\hash_equals($mac, $calculated))
        {
            return null;
        }

        return parent::decrypt($cipherText);
    }
659885
public function decryptWithKey(InputOutputInterface $cipherInputOutput, $recipientId, $privateKey)
    {
        try {
            return $this->cipher->decryptWithKey($cipherInputOutput->getInput(), $recipientId, $privateKey);
        } catch (Exception $exception) {
            throw new CipherException($exception->getMessage(), $exception->getCode());
        }
    }
1006901
private function getKeyManagementMode(JWEInterface $jwe)
    {
        $mode = null;
        $recipients = $jwe->getRecipients();

        foreach ($recipients as $recipient) {
            $complete_headers = array_merge($jwe->getSharedProtectedHeaders(), $jwe->getSharedHeaders(), $recipient->getHeaders());
            Assertion::keyExists($complete_headers, 'alg', 'Parameter "alg" is missing.');

            $key_encryption_algorithm = $this->getJWAManager()->getAlgorithm($complete_headers['alg']);
            Assertion::isInstanceOf($key_encryption_algorithm, Algorithm\KeyEncryptionAlgorithmInterface::class, sprintf('The key encryption algorithm "%s" is not supported or not a key encryption algorithm instance.', $complete_headers['alg']));

            if (null === $mode) {
                $mode = $key_encryption_algorithm->getKeyManagementMode();
            } else {
                Assertion::true($this->areKeyManagementModesCompatible($mode, $key_encryption_algorithm->getKeyManagementMode()), 'Foreign key management mode forbidden.');
            }
        }

        return $mode;
    }
777846
protected function requireToken()
    {
        if (! $this->jwt->setRequest($this->getRequest())->getToken()) {
            throw new JWTException('Token could not be parsed from the request.');
        }

        return $this->jwt;
    }
1338025
public function parseToken($method = 'bearer', $header = 'authorization', $query = 'token')
    {
        if (! $token = $this->parseAuthHeader($header, $method)) {
            if (! $token = $this->request->{$query}) {
                if (! $token = $this->request->header('Token')) {
                    throw new JWTException('The token could not be parsed from the request', 400);
                }
            }
        }

        return $this->setToken($token);
    }
677993
protected function getCrypt()
    {
        static $crypt;

        if (!$crypt) {
            if (empty($this->encodingAESKey) || empty($this->token)) {
                throw new Exception("加密模式下 'encodingAESKey' 与 'token' 都不能为空！");
            }

            $crypt = new Crypt($this->appId, $this->token, $this->encodingAESKey);
        }

        return $crypt;
    }
433832
public function loadUserFromToken()
    {
        $token = $this->httpSession()->get($this->getTokenName());
        if (!$token) {
            return false;
        }

        return $this->decryptUserData($token);
    }
463802
public function with($keyType)
    {

        if (empty($this->action) || empty($this->subject)) {
            throw new \Exception('Must set an action with encrypt() or decrypt()');
        }

        if ($this->key->getType() != CryptoKey::TYPE_PRIVATE) {
            throw new \Exception('Can only specify key to use when using asymmetric cryptogrpahy');
        }

        if ($keyType == self::PUBLIC_KEY) {
            $publicKey = $this->key->getPublicKey(CryptoKey::FORMAT_RAW);
        } elseif ($keyType == self::PRIVATE_KEY) {
            $privateKey = $this->key->getKey(CryptoKey::FORMAT_RAW);
            $privateKey = openssl_pkey_get_private($privateKey);
        }

        $out = '';
        $success = false;

        if ($this->action == self::ACTION_ENCRYPT) {
            if ($keyType == self::PUBLIC_KEY) {
                $success = openssl_public_encrypt($this->subject, $out, $publicKey, OPENSSL_PKCS1_PADDING);
            } elseif ($keyType == self::PRIVATE_KEY) {
                $success = openssl_private_encrypt($this->subject, $out, $privateKey, OPENSSL_PKCS1_PADDING);
            }
        } elseif ($this->action == self::ACTION_DECRYPT) {
            if ($keyType == self::PUBLIC_KEY) {
                $success = openssl_public_decrypt($this->subject, $out, $publicKey, OPENSSL_PKCS1_PADDING);
            } elseif ($keyType == self::PRIVATE_KEY) {
                $success = openssl_private_decrypt($this->subject, $out, $privateKey, OPENSSL_PKCS1_PADDING);
            }
        }

        if (!$success) {
            throw new \Exception('Failure to '. $this->action .' with '. $keyType .' key ('. openssl_error_string() .')');
        }

        return $out;
    }
557874
public function getDecoded()
    {
      if (is_null($this->token)) return null;
      if (is_null($this->decoded)) {
        try {
          $this->decoded = JWT::decode($this->token, $this->key, ['HS512']);
        }
        catch (\Exception $e) {}
        catch (\DomainException $e) {}
      }
      return  $this->decoded;
    }