Verifying Hook Requests via API call.

@param string $payload
@param string $hmac_header

@return bool
@throws \Magento\Framework\Exception\LocalizedException
514248
private function verifyWebhookApi($payload, $hmac_header)
    {
        //Request Data
        $requestData = $this->dataObjectFactory->create();
        $requestData->setApiData(json_decode($payload));
        $requestData->setDynamicApiUrl(ApiHelper::API_VERIFY_SIGNATURE);
        $requestData->setApiKey($this->configHelper->getApiKey());

        $headers = [
            self::HMAC_HEADER => $hmac_header
        ];

        $requestData->setHeaders($headers);

        $requestData->setStatusOnly(true);

        //Build Request
        $request = $this->apiHelper->buildRequest($requestData);
        try {
            $result = $this->apiHelper->sendRequest($request);
        } catch (\Exception $e) {
            return false;
        }

        return $result == 200;
    }
948196
public function parse(): Payload
    {
        /** Check signature from header */
        if (!$this->_checkSignature()) {
            throw new BadSignatureException('Hook secret does not match.');
        }

        /** Get data from different locations according to content-type */
        switch ($this->serverBag->get('CONTENT_TYPE')) {
            case 'application/json':
                $data = $this->getRawData();
                break;

            case 'application/x-www-form-urlencoded':
                $data = $_POST['payload'];
                break;

            default:
                throw new Exception('Unsupported content type: "' . $this->serverBag->get('CONTENT_TYPE') . '"');
        }
        $this->setParsedData($data);

        return $this;
    }
692637
private function isValidResult($payload): bool
    {
        if (!is_array($payload)) {
            return false;
        }

        $headerValid = array_key_exists('jsonrpc', $payload) && $payload['jsonrpc'] === '2.0';
        $resultValid = array_key_exists('result', $payload);
        $idValid     = array_key_exists('id', $payload);

        return $headerValid && $resultValid && $idValid;
    }
1089343
protected function validMac(array $payload)
    {
        $bytes = random_bytes(16);

        $calcMac = hash_hmac('sha256', $this->hash($payload['iv'], $payload['value']), $bytes, true);

        return hash_equals(hash_hmac('sha256', $payload['mac'], $bytes, true), $calcMac);
    }
1031664
protected function validMac(array $payload)
	{
		$bytes = (new SecureRandom)->nextBytes(16);

		$calcMac = hash_hmac('sha256', $this->hash($payload['iv'], $payload['value']), $bytes, true);

		return StringUtils::equals(hash_hmac('sha256', $payload['mac'], $bytes, true), $calcMac);
	}
216442
private static function createJWSAndSign($payload, JWKInterface $signature_key, array $protected_headers = [], $headers = [])
    {
        $jws = self::createJWS($payload);

        $jws = $jws->addSignatureInformation($signature_key, $protected_headers, $headers);

        $complete_headers = array_merge($protected_headers, $headers);
        Assertion::keyExists($complete_headers, 'alg', 'No "alg" parameter set in the header');
        $signer = Signer::createSigner([$complete_headers['alg']]);
        $signer->sign($jws);

        return $jws;
    }
996713
protected function _validMac(array $payload)
    {
        $bytes = function_exists('random_bytes') ? random_bytes(16) : openssl_random_pseudo_bytes(16);
        $calcMac = hash_hmac('sha256', $this->_hash($payload['iv'], $payload['value']), $bytes, true);
        return hash_equals(hash_hmac('sha256', $payload['mac'], $bytes, true), $calcMac);
    }
711312
function verifyHeaders(headers, packetlist) {
  const checkHashAlgos = function(hashAlgos) {
    const check = packet => algo => packet.hashAlgorithm === algo;

    for (let i = 0; i < packetlist.length; i++) {
      if (packetlist[i].tag === enums.packet.signature && !hashAlgos.some(check(packetlist[i]))) {
        return false;
      }
    }
    return true;
  };

  let oneHeader = null;
  let hashAlgos = [];
  headers.forEach(function(header) {
    oneHeader = header.match(/Hash: (.+)/); // get header value
    if (oneHeader) {
      oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace
      oneHeader = oneHeader.split(',');
      oneHeader = oneHeader.map(function(hash) {
        hash = hash.toLowerCase();
        try {
          return enums.write(enums.hash, hash);
        } catch (e) {
          throw new Error('Unknown hash algorithm in armor header: ' + hash);
        }
      });
      hashAlgos = hashAlgos.concat(oneHeader);
    } else {
      throw new Error('Only "Hash" header allowed in cleartext signed message');
    }
  });

  if (!hashAlgos.length && !checkHashAlgos([enums.hash.md5])) {
    throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed');
  } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {
    throw new Error('Hash algorithm mismatch in armor header and signature');
  }
}
1051917
public function onData(Payload $payload)
    {
        $this->received[] = $payload;
        if (($callback = $this->options['on_data_callback'])) {
            call_user_func($callback, $payload);
        }
    }
497004
public function verifyWebhook()
    {
        $payload     = $this->request->getContent();
        $hmac_header = $this->request->getHeader(self::HMAC_HEADER);

        if (!$this->verifyWebhookSecret($payload, $hmac_header) && !$this->verifyWebhookApi($payload, $hmac_header)) {
            throw new WebapiException(__('Precondition Failed'), 6001, 412);
        }
    }
1234087
def create_token(key, payload):
  
  token = hmac.new(key)
  token.update(json.dumps(payload))
  return token.hexdigest()
109238
public function doAction($methodName, $payload, $httpHeaders)
    {
        $this->setHttpHeader($httpHeaders);
        self::$soapClient->__setSoapHeaders($this->getAuthHeader());
        $response = self::$soapClient->$methodName($payload);

        return json_encode($response);
    }
1190684
public function updateUserAsyncWithHttpInfo($user_id, $payload_account)
    {
        $returnType = '';
        $request = $this->updateUserRequest($user_id, $payload_account);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    return [null, $response->getStatusCode(), $response->getHeaders()];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        $response->getBody()
                    );
                }
            );
    }
775010
protected function debugRequest($url, $payload, array $headers)
    {
        if ($this->debug)
        {
            // debug for xterm-compliant cli
            if (php_sapi_name() === 'cli')
            {
                echo PHP_EOL;
                echo "\e[1;33m>>>\e[0;33m [{$url}] \e[1;33m>>>\e[00m" . PHP_EOL;

                foreach ($headers as $value)
                {
                    $matches = array();
                    preg_match('#^(?P<key>[^:\s]+)\s*:\s*(?P<value>.*)$#S', $value, $matches);
                    echo "\e[1;34m{$matches['key']}: \e[0;34m{$matches['value']}\e[00m" . PHP_EOL;
                }
                echo PHP_EOL;
                echo (is_array($payload))
                    ? json_encode($payload, JSON_PRETTY_PRINT)
                    : ((is_null($json = json_decode($payload)))
                        ? $payload :
                        json_encode($json, JSON_PRETTY_PRINT)
                    );

                echo PHP_EOL;
            }
            // debug for the rest
            else
            {
                echo ">>> [{$url}] >>>" . PHP_EOL;
                $message = print_r(is_null($json = json_decode($payload)) ? $payload : $json, true);
                echo $message . (strpos($message, PHP_EOL) ? null : PHP_EOL);
            }
        }
    }
649911
protected function _basicAuth($header)
    {
        if (empty($header)) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception('The value of the client Authorization header is required');
        }
        if (empty($this->_basicResolver)) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception('A basicResolver object must be set before doing Basic '
                                                . 'authentication');
        }

        // Decode the Authorization header
        $auth = substr($header, strlen('Basic '));
        $auth = base64_decode($auth);
        if (!$auth) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception('Unable to base64_decode Authorization header value');
        }

        // See ZF-1253. Validate the credentials the same way the digest
        // implementation does. If invalid credentials are detected,
        // re-challenge the client.
        if (!ctype_print($auth)) {
            return $this->_challengeClient();
        }
        // Fix for ZF-1515: Now re-challenges on empty username or password
        $creds = array_filter(explode(':', $auth));
        if (count($creds) != 2) {
            return $this->_challengeClient();
        }

        $password = $this->_basicResolver->resolve($creds[0], $this->_realm);
        if ($password && $this->_secureStringCompare($password, $creds[1])) {
            $identity = array('username'=>$creds[0], 'realm'=>$this->_realm);
            return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity);
        } else {
            return $this->_challengeClient();
        }
    }
1084848
public function has(Payload $payload)
    {
        $val = $this->storage->get($this->getKey($payload));

        // exit early if the token was blacklisted forever,
        if ($val === 'forever') {
            return true;
        }

        // check whether the expiry + grace has past
        return ! empty($val) && ! Utils::isFuture($val['valid_until']);
    }
829053
protected function respondToClient(string $address, string $payload = '')
    {
        try {
            $clientSocket = $this->clientSocket->getWrappedSocket();
            $clientSocket->send($address, \ZMQ::MODE_SNDMORE);
            $clientSocket->send('', \ZMQ::MODE_SNDMORE);
            $clientSocket->send($payload);
        } catch (\ZMQException $e) {
            $this->logger->error('Error respoding to client: ' . $e->getMessage());
        }
    }