Encode a token.

@param int|null   $lifetime      The lifetime in seconds this token shall be valid. Use null for no limit.

@param null|array $customPayload Any custom payload to be added to the token.

@return string
172119
private function encode($lifetime, $customPayload = null)
    {
        $time    = time();
        $payload = ['iat' => $time];

        if (null !== $customPayload) {
            $payload = array_merge($customPayload, $payload);
        }

        $jti = md5(json_encode($payload));

        $payload['jti'] = $jti;

        if (null !== $this->localId) {
            $payload['aud'] = $this->localId;
        }

        if (null !== $lifetime) {
            $payload['exp'] = ($time + $lifetime);
        }

        $jwt = \JWT::encode($payload, $this->secret);

        return $jwt;
    }
539866
public static function load($jwsTokenString, $allowUnsecure = false, Encoder $encoder = null, $encryptionEngine = 'OpenSSL')
    {
        if ($encoder === null) {
            $encoder = strpbrk($jwsTokenString, '+/=') ? new Base64Encoder() : new Base64UrlSafeEncoder();
        }

        $parts = explode('.', $jwsTokenString);

        if (count($parts) === 3) {
            $header = json_decode($encoder->decode($parts[0]), true);
            $payload = json_decode($encoder->decode($parts[1]), true);

            if (is_array($header) && is_array($payload)) {
                if (strtolower($header['alg']) === 'none' && !$allowUnsecure) {
                    throw new InvalidArgumentException(sprintf('The token "%s" cannot be validated in a secure context, as it uses the unallowed "none" algorithm', $jwsTokenString));
                }

                $jws = new static($header, $encryptionEngine);

                $jws->setEncoder($encoder)
                    ->setHeader($header)
                    ->setPayload($payload)
                    ->setOriginalToken($jwsTokenString)
                    ->setEncodedSignature($parts[2]);

                return $jws;
            }
        }

        throw new InvalidArgumentException(sprintf('The token "%s" is an invalid JWS', $jwsTokenString));
    }
840035
public static function createJWSWithDetachedPayloadToCompactJSON($payload, JWKInterface $signature_key, array $protected_headers, LoggerInterface $logger = null)
    {
        $jws = self::createJWSWithDetachedPayloadAndSign($payload, $signature_key, $protected_headers, [], $logger);

        return $jws->toCompactJSON(0);
    }
178421
private function isExpired($createTs, $lifetime) {
    if ($lifetime === null) {
      return false;
    }
    $expireDate = (new \DateTime())->setTimeStamp($createTs);
    if (intval($lifetime)) {
      $expireDate = $expireDate->modify('+'.$lifetime.' seconds');
    }
    return $expireDate < new \DateTime();
  }
1042134
private function _prepareData($data, $lifetime, $priority)
    {
        $lt = $lifetime;
        if ($lt === null) {
            $lt = 9999999999;
        }
        return serialize(array(
            'data' => $data,
            'lifetime' => $lifetime,
            'expire' => time() + $lt,
            'priority' => $priority
        ));
    }
828060
public static function generateWithCustomAlphabet($customAlphabet = '0123456789ABCDEF', $tokenLength = 32) {

        // Set initial alphabet.
        $generator = new RandomStringGenerator($customAlphabet);

        // Change alphabet whenever needed.
        //$generator->setAlphabet($customAlphabet);
        // Call method to generate random string.
        $token = $generator->generate($tokenLength);

        return $token;
    }
1150699
private function createSignature(&$json) 
    {
        $string = $this->appId . $this->method . $this->endpoint;
        
        if ($json) {
            $string .= $json;
        }
        
        if ($this->accessToken) {
            $string .= $this->accessToken;
        }
        
        $digest = hash("sha512", $string);
      
        $sign = "";
        $result = openssl_public_encrypt($digest, $sign, $this->secretKey, OPENSSL_PKCS1_OAEP_PADDING);

        if (!$result) {
            throw new EndpointException("Request signing failed");
        }
        
        return rawurlencode(base64_encode($sign));
    }
729986
public static JWTPayload getPayload(String tokenString) {
        JWTPayload payload = null;
        String[] jwtParts = splitTokenString(tokenString);
        if (jwtParts.length >= 2) {
            WSJsonToken token = deserialize(jwtParts, tokenString);
            payload = new JWTPayload();
            fromJsonToken(token, payload);
        }
        return payload;
    }
378847
protected function generatePayload($nonce, $iat, $exp)
    {
        $payload = new \stdClass();
        $payload->nonce = $nonce;
        $payload->iat = $iat;
        $payload->ttl = $exp - $iat;
        $payload->exp = $exp;

        return $payload;
    }
138729
public static function get(
        int $paymentServiceProviderCredentialId,
        array $customHeaders = []
    ): BunqResponsePaymentServiceProviderCredential {
        $apiClient = new ApiClient(static::getApiContext());
        $responseRaw = $apiClient->get(
            vsprintf(
                self::ENDPOINT_URL_READ,
                [$paymentServiceProviderCredentialId]
            ),
            [],
            $customHeaders
        );

        return BunqResponsePaymentServiceProviderCredential::castFromBunqResponse(
            static::fromJson($responseRaw, self::OBJECT_TYPE_GET)
        );
    }
574798
protected function encodeSingleResource(
        \FreeFW\Interfaces\ApiResponseInterface $p_api_response
    ) : \FreeFW\JsonApi\V1\Model\ResourceObject {
        $resource = new \FreeFW\JsonApi\V1\Model\ResourceObject(
            $p_api_response->getApiType(),
            $p_api_response->getApiId()
        );
        $fields = $p_api_response->getApiAttributes();
        if ($fields) {
            $attributes = new \FreeFW\JsonApi\V1\Model\AttributesObject($fields);
            $resource->setAttributes($attributes);
        }
        return $resource;
    }
364075
public static function jwtGetEncryptedPayload(array $payload,
                                                  string $encryptionKey,
                                                  ViewHandlerInterface $viewHandler
    ): Response
    {
        return ResponseHelper::Serialize(
            [
                'encryptedPayload' => CryptoHelper::encryptArrayToBase64(
                    $payload,
                    $encryptionKey
                )
            ],
            $viewHandler
        );
    }
8848
private function initPayload($text)
    {
        $payload = new Payload();
        $payload->setOptions($this->getOptions());
        $payload->setQueryText($text);
        return $payload->createPayload();
    }
804997
public function set($key, $value, $lifeTime = 3600)
    {
        if (!$this->isEnabled()) {
            return false;
        }

        return $this->server->set($this->prefix . $key, $value, false, $lifeTime);
    }
680077
protected ChainedResourceBundlePostProcessor getCustomProcessorWrapper(ResourceBundlePostProcessor customProcessor,
			String key, boolean isVariantPostProcessor) {
		return new CustomPostProcessorChainWrapper(key, customProcessor, isVariantPostProcessor);
	}
797793
public function getPresignedUri($path, $expires = '+30 minutes')
    {
        if (preg_match('#^s3://(.*?)/(.*)$#', $path, $matches)) {
            $bucket = $matches[1];
            $path   = $matches[2];
        }
        else {
            throw new \InvalidArgumentException("path should be a full path starting with s3://");
        }
        $path = ltrim($path, "/");
        $path = preg_replace('#/+#', '/', $path);
        
        $cmd = $this->getCommand(
            'GetObject',
            [
                "Bucket" => $bucket,
                "Key"    => $path,
            ]
        );
        $req = $this->createPresignedRequest($cmd, $expires);
        
        return strval($req->getUri());
    }
1108357
public function sendPayload($payload, $callback)
    {
        if (!is_string($payload)) {
            throw new \InvalidArgumentException('Payload must be string.');
        }

        try {
            $res = $this->client->post($this->host, [
                'headers' => [
                    'content-type' => 'application/json'
                ],
                'body' => $payload,
                'timeout' => $this->timeout,
                'connect_timeout' => $this->timeout
            ]);
            /**
             * @var StreamInterface $stream ;
             */
            $stream = $res->getBody();
            $json = json_decode($stream);
            $stream->close();

            if (JSON_ERROR_NONE !== json_last_error()) {
                call_user_func($callback, new InvalidArgumentException('json_decode error: ' . json_last_error_msg()), null);
            }
            if (is_array($json)) {
                // batch results
                $results = [];
                $errors = [];

                foreach ($json as $result) {
                    if (property_exists($result,'result')) {
                        $results[] = $result->result;
                    } else {
                        if (isset($json->error)) {
                            $error = $json->error;
                            $errors[] = new RPCException(mb_ereg_replace('Error: ', '', $error->message), $error->code);
                        } else {
                            $results[] = null;
                        }
                    }
                }
                if (count($errors) > 0) {
                    call_user_func($callback, $errors, $results);
                } else {
                    call_user_func($callback, null, $results);
                }
            } elseif (property_exists($json,'result')) {
                call_user_func($callback, null, $json->result);
            } else {
                if (isset($json->error)) {
                    $error = $json->error;

                    call_user_func($callback, new RPCException(mb_ereg_replace('Error: ', '', $error->message), $error->code), null);
                } else {
                    call_user_func($callback, new RPCException('Something wrong happened.'), null);
                }
            }
        } catch (RequestException $err) {
            call_user_func($callback, $err, null);
        }
    }