@param object|array $payload PHP object or array
@param string $key The secret key
@param string $algo The signing algorithm
@param array $additionalHeaders Additional keys/values to add to the header

@return string A JWT
778284
public static function encode($payload, $key, $algo = 'HS256', $additionalHeaders = array()) {
        $header = array('typ' => 'JWT', 'alg' => $algo);
        $header = $header + $additionalHeaders;

        $segments = array();
        $segments[] = self::urlsafeB64Encode(self::jsonEncode($header));
        $segments[] = self::urlsafeB64Encode(self::jsonEncode($payload));
        $signing_input = implode('.', $segments);

        $signature = self::sign($signing_input, $key, $algo);
        $segments[] = self::urlsafeB64Encode($signature);

        return implode('.', $segments);
    }
1013699
function signedRequestHeaders(apiKey, apiSecretKey, apiUserToken, options) {
  if (!apiKey || !apiSecretKey || !apiUserToken) {
    return false;
  }
  var apiExpDate = Math.floor(Date.now() / 1000) + 600;
  var payload = apiKey + apiUserToken + apiExpDate;
  var hash = CryptoJS.HmacSHA256(payload, apiSecretKey);
  var headers = {
    'x-api-key': apiKey,
    'x-api-user-token': apiUserToken,
    'x-api-signature': 'Method=HMAC-SHA256 Signature=' + hash,
    'x-api-exp-date': apiExpDate,
  };
  return headers;
}
147321
public static function createFromSecret(string $secret, array $additional_values = []): JWK
    {
        $values = \array_merge(
            $additional_values,
            [
                'kty' => 'oct',
                'k' => Base64Url::encode($secret),
            ]
        );

        return JWK::create($values);
    }
785510
public static function generateToken($payload = null)
    {
        if (empty($payload)) {
            return false;
        }

        $token = JWT::encode($payload, Configure::read('ApiRequest.jwtAuth.cypherKey'), Configure::read('ApiRequest.jwtAuth.tokenAlgorithm'));

        return $token;
    }
1007477
public function encode(Payload $payload)
    {
        $token = $this->jwt->encode($payload->get());

        return new Token($token);
    }
498287
protected function parseSignature(array $header, $data)
    {
        if ($data == '' || !isset($header['alg']) || $header['alg'] == 'none') {
            return null;
        }

        $hash = $this->deserializer->fromBase64URL($data);

        return new Signature($hash);
    }
1086663
public function addSignature(JWK $signatureKey, array $protectedHeader, array $header = []): self
    {
        $this->checkB64AndCriticalHeader($protectedHeader);
        $isPayloadEncoded = $this->checkIfPayloadIsEncoded($protectedHeader);
        if (null === $this->isPayloadEncoded) {
            $this->isPayloadEncoded = $isPayloadEncoded;
        } elseif ($this->isPayloadEncoded !== $isPayloadEncoded) {
            throw new \InvalidArgumentException('Foreign payload encoding detected.');
        }
        $this->checkDuplicatedHeaderParameters($protectedHeader, $header);
        KeyChecker::checkKeyUsage($signatureKey, 'signature');
        $signatureAlgorithm = $this->findSignatureAlgorithm($signatureKey, $protectedHeader, $header);
        KeyChecker::checkKeyAlgorithm($signatureKey, $signatureAlgorithm->name());
        $clone = clone $this;
        $clone->signatures[] = [
            'signature_algorithm' => $signatureAlgorithm,
            'signature_key' => $signatureKey,
            'protected_header' => $protectedHeader,
            'header' => $header,
        ];

        return $clone;
    }
1282904
public function sign($payload, $key)
    {
        if (!$key instanceof Key) {
            $key = new Key($key);
        }
        $privateKey = $this->keyParser->parsePrivateKey($key->getContent());

        $hash = $this->hash($payload);

        $random = RandomGeneratorFactory::getRandomGenerator();
        $randomK = $random->generate($this->config->getGenerator()->getOrder());

        $signer = new EccSigner($this->adapter);
        $signature = $signer->sign($privateKey, $hash, $randomK);

        return new LcobucciJWTSignature($this->serializer->serialize($signature, $this->config->getSignatureLength()));
    }
355096
private function verifySignature(Object\JWSInterface $jws, Object\JWKSetInterface $jwk_set, Object\SignatureInterface $signature, $detached_payload = null)
    {
        $input = $this->getInputToVerify($jws, $signature, $detached_payload);
        foreach ($jwk_set->getKeys() as $jwk) {
            $algorithm = $this->getAlgorithm($signature);

            try {
                $this->checkKeyUsage($jwk, 'verification');
                $this->checkKeyAlgorithm($jwk, $algorithm->getAlgorithmName());
                if (true === $algorithm->verify($jwk, $input, $signature->getSignature())) {
                    return true;
                }
            } catch (\Exception $e) {
                //We do nothing, we continue with other keys
                continue;
            }
        }

        return false;
    }
1055586
public static function fromSignatureData(string $data,
        AlgorithmIdentifierType $algo): Signature
    {
        if ($algo instanceof RSASignatureAlgorithmIdentifier) {
            return RSASignature::fromSignatureString($data);
        }
        if ($algo instanceof ECSignatureAlgorithmIdentifier) {
            return ECSignature::fromDER($data);
        }
        return new GenericSignature(new BitString($data), $algo);
    }
440237
public function addToken($name, array $payload, $secret) {
        $this->jwtTokens[$name] = [
            'payload' => $payload,
            'secret' => $secret,
        ];

        return $this;
    }
335572
public function validate($secret = null, $algo = null)
    {
        $token = $this->token();
        $secret = $secret ?: $this->secret();
        $algo = $algo ?: $this->algorithm();

        return $this->jwt->validateToken($token, $secret, $algo);
    }
1110217
private function sign(array $payload): string
    {
        $jsonConverter = new StandardConverter();
        $payload = array_merge(
            $payload,
            $this->getAdditionalPayload()
        );
        $headers = $this->getSignatureHeader();
        $signatureKey = $this->signatureKeyset->get($this->signatureKeyIndex);
        if ($signatureKey->has('kid')) {
            $headers['kid'] = $signatureKey->get('kid');
        }

        $jws = $this->jwsBuilder
            ->create()
            ->withPayload($jsonConverter->encode($payload))
            ->addSignature($signatureKey, $headers)
            ->build();

        $serializer = new JWSCompactSerializer($jsonConverter);

        return $serializer->serialize($jws, 0);
    }
500487
private function sign_headers($headers) {
        if(is_array($headers)){
            ksort($headers);
            $result = array();
            foreach($headers as $key=>$value){
                if ( ($key == 'Authorization') || (substr($key, 0, 6)=='X-Api-') ) {
                    $result[] = $key.'='.$value;
                }
            }
            return implode('&', $result);
        }
    }
553175
def _from_jwt(cls, headers, payload, key=None):
        
        jwt = Jwt(
            secret_key=key,
            issuer=payload.get('iss', None),
            subject=payload.get('sub', None),
            algorithm=headers.get('alg', None),
            valid_until=payload.get('exp', None),
            nbf=payload.get('nbf', None),
        )
        jwt.__decoded_payload = payload
        jwt.__decoded_headers = headers
        return jwt
620007
public function hmac($algo, $data, $key, $raw_output = false)
    {
        return hash_hmac($algo, $data, $key, $raw_output);
    }
1026032
public static function customPayload(array $payload, string $secret): string
    {
        $builder = self::builder();

        foreach ($payload as $key => $value) {
            if (is_int($key)) {
                throw new ValidateException('Invalid payload claim.', 8);
            }

            $builder->setPayloadClaim($key, $value);
        }

        return $builder->setSecret($secret)
            ->build()
            ->getToken();
    }