@param string $signature
@param string $data
@param string $secret

@return bool
439266
public function verify(string $signature, string $data, string $secret): bool
    {
        $compareSignature = $this->sign($data, $secret);

        return $compareSignature === $signature;
    }
1081379
public static function authenticateThenDecrypt($secret, $body, $signature) {
    $keys = self::deriveAesKeys($secret);

    $localHmac = hash_hmac('sha256', $body, $keys['auth']);
    if (!self::hash_compare($signature, $localHmac)) {
      throw new InvalidMessageException("Incorrect hash");
    }

    list ($jsonEnvelope, $jsonEncrypted) = explode(Constants::PROTOCOL_DELIM, $body, 2);
    if (strlen($jsonEnvelope) > Constants::MAX_ENVELOPE_BYTES) {
      throw new InvalidMessageException("Oversized envelope");
    }

    $envelope = json_decode($jsonEnvelope, TRUE);
    if (!$envelope) {
      throw new InvalidMessageException("Malformed envelope");
    }

    if (!is_numeric($envelope['ttl']) || Time::getTime() > $envelope['ttl']) {
      throw new InvalidMessageException("Invalid TTL");
    }

    if (!is_string($envelope['iv']) || strlen($envelope['iv']) !== Constants::AES_BYTES * 2 || !preg_match('/^[a-f0-9]+$/', $envelope['iv'])) {
      // AES_BYTES (32) ==> bin2hex ==> 2 hex digits (4-bit) per byte (8-bit)
      throw new InvalidMessageException("Malformed initialization vector");
    }

    $jsonPlaintext = UserError::adapt('Civi\Cxn\Rpc\Exception\InvalidMessageException', function () use ($jsonEncrypted, $envelope, $keys) {
      $cipher = new \Crypt_AES(CRYPT_AES_MODE_CBC);
      $cipher->setKeyLength(Constants::AES_BYTES);
      $cipher->setKey($keys['enc']);
      $cipher->setIV(BinHex::hex2bin($envelope['iv']));
      return $cipher->decrypt($jsonEncrypted);
    });
    return $jsonPlaintext;
  }
807166
public function generateWebhookSignature(
        string $url,
        \stdClass $data,
        string $secret_key
    ) {
        $signature = $url;
        $signature .= json_encode($data);

        return base64_encode(hash_hmac('sha1', $signature, $secret_key, true));
    }
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);
    }
405307
private static function hmacFallbackMD5($data, $secret) {
    $b = 64; // byte length for md5

    if (strlen($secret) > $b) {
      $secret = pack("H*", md5($secret));
    }

    $secret = str_pad($secret, $b, chr(0x00));
    $ipad = str_pad('', $b, chr(0x36));
    $opad = str_pad('', $b, chr(0x5c));
    $k_ipad = $secret ^ $ipad;
    $k_opad = $secret ^ $opad;

    return md5($k_opad . pack("H*", md5($k_ipad . $data)));
  }
51010
private function getPHPECCSignature(JWKInterface $key, $data)
    {
        $p = $this->getGenerator();
        $d = $this->convertBase64ToGmp($key->get('d'));
        $hash = $this->convertHexToGmp(hash($this->getHashAlgorithm(), $data));

        $k = RandomGeneratorFactory::getRandomGenerator()->generate($p->getOrder());

        $signer = EccFactory::getSigner();

        $private_key = $p->getPrivateKeyFrom($d);
        $signature = $signer->sign($private_key, $hash, $k);

        $part_length = $this->getSignaturePartLength();

        $R = str_pad($this->convertDecToHex($signature->getR()), $part_length, '0', STR_PAD_LEFT);
        $S = str_pad($this->convertDecToHex($signature->getS()), $part_length, '0', STR_PAD_LEFT);

        return $this->convertHexToBin($R.$S);
    }
1088462
public static function verifySign(array $data, $sync = false, $sign = null): bool
    {
        $publicKey = self::$instance->ali_public_key;

        if (is_null($publicKey)) {
            throw new InvalidConfigException('Missing Alipay Config -- [ali_public_key]');
        }

        if (Str::endsWith($publicKey, '.pem')) {
            $publicKey = openssl_pkey_get_public($publicKey);
        } else {
            $publicKey = "-----BEGIN PUBLIC KEY-----\n".
                wordwrap($publicKey, 64, "\n", true).
                "\n-----END PUBLIC KEY-----";
        }

        $sign = $sign ?? $data['sign'];

        $toVerify = $sync ? mb_convert_encoding(json_encode($data, JSON_UNESCAPED_UNICODE), 'gb2312', 'utf-8') :
                            self::getSignContent($data, true);

        return openssl_verify($toVerify, base64_decode($sign), $publicKey, OPENSSL_ALGO_SHA256) === 1;
    }
197519
public function validateToken($token, $secret, $algorithm = 'HS256')
    {
        try {
            JWT::decode($token, $secret, [$algorithm]);
        } catch(\Exception $e) {
            return false;
        }

        return true;
    }
1199037
public function validateSignature(string $secret, SignatureValidator $validator)
    {
        if (!$validator->isValid($this->payload, $secret, $this->signature)) {
            throw new \InvalidArgumentException("Invalid signature");
        }
    }
667807
public static function verifyRsa(string $data, string $signature, string $publicKey, string $format = null): bool
    {
        $signature = self::toRaw($signature, $format);
        $key = \openssl_pkey_get_public($publicKey);

        $return = \openssl_verify($data, $signature, $key, OPENSSL_ALGO_SHA256);
        if ($return === -1) {
            throw new CryptoException('RSA signature check error: ' . openssl_error_string());
        }

        return $return === 1;
    }
726883
protected function generateSignature($params, $secret) {
    // Work with sorted data.
    ksort($params);

    // Generate the base string.
    $base_string = '';
    foreach ($params as $key => $value) {
      $base_string .= $key . '=' . $value;
    }
    $base_string .= $secret;

    return md5($base_string);
  }
153261
public function isValid($payload, $secret, $signature)
    {
        return $signature === hash_hmac($this->hashAlgorithm, $payload, $secret, true);
    }
238295
public function mpsDecode($data_encrypted, $signature)
    {
        try {
            $inputParams = [
                'data_encrypted' => $data_encrypted,
                'signature'      => $signature,
            ];
            $this->debug->info(__FUNCTION__, 'Input Params: ' . json_encode($inputParams));
            $viettelMps = new ViettelMps\ViettelMps($this->options);
            $viettelMps->setViettelPublicKey($this->viettelPublicKey);
            $viettelMps->setViettelPrivateKey($this->viettelPrivateKey);
            $viettelMps->setCpPublicKey($this->cpPublicKey);
            $viettelMps->setCpPrivateKey($this->cpPrivateKey);
            $response = $viettelMps->decodeResponseFromMps($data_encrypted, $signature);
            $this->debug->info(__FUNCTION__, 'decode Response From Mps: ' . json_encode($response));
            if (isset($response) && $response !== NULL && count($response) > 0) {
                if ($this->nativeSession === TRUE) {
                    $this->debug->info(__FUNCTION__, 'Viettel Set Session MSISDN Native: ' . json_encode($response['msisdn']));
                    Session::setUserdata(self::SESSION_MSISDN_DEFAULT, $response['msisdn']);
                }
                if ($response['msisdn'] == "" || $response['msisdn'] == "GUEST") {
                    // Không nhận diện được thuê bao
                    $mpsResult = [
                        'status' => 1,
                        'msisdn' => NULL
                    ];
                } else {
                    // Nhận diện được thuê bao
                    $mpsResult = [
                        'status'       => 0,
                        'msisdn'       => $response['msisdn'],
                        'request_ip'   => $response['request_ip'],
                        'request_id'   => $response['request_id'],
                        'response_id'  => $response['response_id'],
                        'price'        => $response['price'],
                        'source'       => $response['source'],
                        'command'      => $response['command'],
                        'content_logs' => $response['content_logs']
                    ];
                    if ($this->nativeSession === TRUE) {
                        $this->debug->info(__FUNCTION__, 'set native Session Mps Result');
                        Session::setUserdata(self::SESSION_MPS_RESULT, json_encode($mpsResult));
                    }
                }
                $this->debug->info(__FUNCTION__, 'MPS Result: ' . json_encode($mpsResult));

                return $mpsResult;
            } else {
                $this->debug->info(__FUNCTION__, 'MPS Not Response or Response is Empty');

                return NULL;
            }
        }
        catch (\Exception $e) {
            $message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
            $this->debug->error(__FUNCTION__, $message);

            return NULL;
        }
    }
255340
public function parse($query, $secret = null)
    {
        $secret = $secret ? Secret::create($secret) : $this->secret;
        if (null === $secret) {
            throw new \RuntimeException('Secret not set on instance, be sure to pass it on parse.');
        }

        $query = is_array($query) ? new QueryString($query) : QueryString::fromString($query);

        if (! $query->isValid($secret)) {
            throw new \RuntimeException('Bad signature for payload.');
        }

        $data = QueryString::fromString(base64_decode($query['sso']));

        return new Payload($data->all() + [ 'sso_secret' => $secret ]);
    }
81773
private function check_signature($consumerkey, $secret, $body) {

        $ok = true;
        try {
            // TODO: Switch to core oauthlib once implemented - MDL-30149.
            lti\handle_oauth_body_post($consumerkey, $secret, $body);
        } catch (\Exception $e) {
            debugging($e->getMessage() . "\n");
            $ok = false;
        }

        return $ok;

    }
199083
public function verifySignature($data, $signature)
    {
        switch ($this->cryptParams['library']) {
            case 'openssl':
                return $this->verifyOpenSSL($data, $signature);
            case (self::HMAC_SHA1):
                $expectedSignature = hash_hmac("sha1", $data, $this->key, true);
                return strcmp($signature, $expectedSignature) == 0;
        }
    }