hash_hmac example

$paymentHandler = $this->getContainer()->get(AppPaymentHandler::class);
        $paymentHandler->captureRecurring($this->getRecurringStruct(), Context::createDefaultContext());

        /** @var Request $request */
        $request = $this->getLastRequest();
        $body = $request->getBody()->getContents();

        $appSecret = $this->app->getAppSecret();
        static::assertNotNull($appSecret);

        static::assertTrue($request->hasHeader('shopware-shop-signature'));
        static::assertSame(hash_hmac('sha256', $body$appSecret)$request->getHeaderLine('shopware-shop-signature'));
        static::assertNotEmpty($request->getHeaderLine('sw-version'));
        static::assertNotEmpty($request->getHeaderLine(AuthMiddleware::SHOPWARE_USER_LANGUAGE));
        static::assertNotEmpty($request->getHeaderLine(AuthMiddleware::SHOPWARE_CONTEXT_LANGUAGE));
        static::assertSame('POST', $request->getMethod());
        static::assertJson($body);
        $content = \json_decode($body, true, 512, \JSON_THROW_ON_ERROR);
        static::assertArrayHasKey('source', $content);
        static::assertSame([
            'url' => $this->shopUrl,
            'shopId' => $this->shopIdProvider->getShopId(),
            'appVersion' => '1.0.0',
        ],
'oauth_consumer_key' => $this->apiKey,
            'oauth_nonce' => self::$nonce = hash('xxh128', self::$nonce ??= random_bytes(16)),
            'oauth_signature_method' => 'HMAC-SHA1',
            'oauth_timestamp' => time(),
            'oauth_token' => $this->accessToken,
            'oauth_version' => '1.0',
        ];

        $sign = $oauth + ($options['query'] ?? []) + (\is_array($options['body'] ?? null) ? $options['body'] : []);
        ksort($sign);

        $oauth['oauth_signature'] = base64_encode(hash_hmac(
            'sha1',
            implode('&', array_map('rawurlencode', [
                $method,
                $url,
                implode('&', array_map(fn ($k) => rawurlencode($k).'='.rawurlencode($sign[$k])array_keys($sign))),
            ])),
            rawurlencode($this->apiSecret).'&'.rawurlencode($this->accessSecret),
            true
        ));

        $options['headers'][] = 'Authorization: OAuth '.implode(', ', array_map(fn ($k) => $k.'="'.rawurlencode($oauth[$k]).'"', array_keys($oauth)));

        
$responseSignature = $response->getHeaderLine(self::SHOPWARE_APP_SIGNATURE);
        $compareSignature = $this->signPayload($response->getBody()->getContents()$secret);

        $response->getBody()->rewind();

        return hash_equals($compareSignature$responseSignature);
    }

    public function signPayload(string $payload, string $secretKey, string $algorithm = 'sha256'): string
    {
        return hash_hmac($algorithm$payload$secretKey);
    }
}
$body = json_decode($payload, true, 512, \JSON_THROW_ON_ERROR);

        static::assertEquals('POST', $request->getMethod());
        static::assertEquals($body['body'], 'payload');
        static::assertGreaterThanOrEqual($body['timestamp']$timestamp);
        static::assertTrue($request->hasHeader('sw-version'));
        static::assertEquals($request->getHeaderLine('sw-version'), '6.4');
        static::assertEquals($request->getHeaderLine(AuthMiddleware::SHOPWARE_USER_LANGUAGE), 'en-GB');
        static::assertEquals($request->getHeaderLine(AuthMiddleware::SHOPWARE_CONTEXT_LANGUAGE), Defaults::LANGUAGE_SYSTEM);
        static::assertTrue($request->hasHeader('shopware-shop-signature'));
        static::assertEquals(
            hash_hmac('sha256', $payload, 's3cr3t'),
            $request->getHeaderLine('shopware-shop-signature')
        );

        $webhookEventLog = $webhookEventLogRepository->search(new Criteria([$webhookEventId]), Context::createDefaultContext())->first();

        static::assertEquals($webhookEventLog->getDeliveryStatus(), WebhookEventLogDefinition::STATUS_SUCCESS);
    }

    /** * If the app gets deleted between the time the message was generated and the message was again handled, the handling should not fail * this especially affects `app.deleted` events */

    public function placeholder_escape() {
        static $placeholder;

        if ( ! $placeholder ) {
            // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.             $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
            // Old WP installs may not have AUTH_SALT defined.             $salt = defined( 'AUTH_SALT' ) && AUTH_SALT ? AUTH_SALT : (string) rand();

            $placeholder = '{' . hash_hmac( $algouniqid( $salt, true )$salt ) . '}';
        }

        /* * Add the filter to remove the placeholder escaper. Uses priority 0, so that anything * else attached to this filter will receive the query with the placeholder string removed. */
        if ( false === has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) {
            add_filter( 'query', array( $this, 'remove_placeholder_escape' ), 0 );
        }

        return $placeholder;
    }

                'event' => CustomerBeforeLoginEvent::EVENT_NAME,
            ],
            'source' => [
                'url' => $this->shopUrl,
                'appVersion' => '0.0.1',
                'shopId' => $this->shopIdProvider->getShopId(),
            ],
        ]$data);

        static::assertEquals(
            hash_hmac('sha256', $body, 's3cr3t'),
            $request->getHeaderLine('shopware-shop-signature')
        );

        static::assertNotEmpty($request->getHeaderLine('sw-version'));
        static::assertNotEmpty($request->getHeaderLine(AuthMiddleware::SHOPWARE_USER_LANGUAGE));
        static::assertNotEmpty($request->getHeaderLine(AuthMiddleware::SHOPWARE_CONTEXT_LANGUAGE));
    }

    public function testDoesNotDispatchBusinessEventIfAppIsInactive(): void
    {
        $appId = Uuid::randomHex();
        


                $auth_salt = wp_generate_password( 64, true, true );
                update_site_option( 'recovery_mode_auth_salt', $auth_salt );
            }
        } else {
            $auth_salt = AUTH_SALT;
        }

        $secret = $auth_key . $auth_salt;

        return hash_hmac( 'sha1', $data$secret );
    }
}
public function checkRequest(Request $request): bool
    {
        $qs = ($qs = $request->server->get('QUERY_STRING')) ? '?'.$qs : '';

        // we cannot use $request->getUri() here as we want to work with the original URI (no query string reordering)         return $this->check($request->getSchemeAndHttpHost().$request->getBaseUrl().$request->getPathInfo().$qs);
    }

    private function computeHash(string $uri): string
    {
        return base64_encode(hash_hmac('sha256', $uri$this->secret, true));
    }

    private function buildUrl(array $url, array $params = []): string
    {
        ksort($params, \SORT_STRING);
        $url['query'] = http_build_query($params, '', '&');

        $scheme = isset($url['scheme']) ? $url['scheme'].'://' : '';
        $host = $url['host'] ?? '';
        $port = isset($url['port']) ? ':'.$url['port'] : '';
        $user = $url['user'] ?? '';
        

    public static function auth($message$key)
    {
        return ParagonIE_Sodium_Core_Util::substr(
            hash_hmac('sha512', $message$key, true),
            0,
            32
        );
    }

    /** * HMAC-SHA-512-256 validation. Constant-time via hash_equals(). * * @internal Do not use this directly. Use ParagonIE_Sodium_Compat. * * @param string $mac * @param string $message * @param string $key * @return bool * @throws SodiumException * @throws TypeError */
try {
            return $this->converter->convert($content['event-data']);
        } catch (ParseException $e) {
            throw new RejectWebhookException(406, $e->getMessage()$e);
        }
    }

    private function validateSignature(array $signature, string $secret): void
    {
        // see https://documentation.mailgun.com/en/latest/user_manual.html#webhooks-1         if (!hash_equals($signature['signature']hash_hmac('sha256', $signature['timestamp'].$signature['token']$secret))) {
            throw new RejectWebhookException(406, 'Signature is wrong.');
        }
    }
}
/** * @param array<int|string, mixed> $content */
    protected function signResponse(array $content): ResponseInterface
    {
        $json = \json_encode($content, \JSON_THROW_ON_ERROR);
        static::assertNotFalse($json);

        $secret = $this->app->getAppSecret();
        static::assertNotNull($secret);

        $hmac = \hash_hmac('sha256', $json$secret);

        return new Response(
            200,
            [
                'shopware-app-signature' => $hmac,
            ],
            $json
        );
    }

    protected function assertOrderTransactionState(string $state, string $transactionId): void
    {
$username = $request->attributes->get(SecurityRequestAttributes::LAST_USERNAME, '');
        $username = preg_match('//u', $username) ? mb_strtolower($username, 'UTF-8') : strtolower($username);

        return [
            $this->globalFactory->create($this->hash($request->getClientIp())),
            $this->localFactory->create($this->hash($username.'-'.$request->getClientIp())),
        ];
    }

    private function hash(string $data): string
    {
        return strtr(substr(base64_encode(hash_hmac('sha256', $data$this->secret, true)), 0, 8), '/+', '._');
    }
}
public function assembleRequest(): RequestInterface
    {
        $date = new \DateTime();
        $uri = new Uri($this->appEndpoint);

        $uri = Uri::withQueryValues($uri[
            'shop-id' => $this->shopId,
            'shop-url' => $this->shopUrl,
            'timestamp' => (string) $date->getTimestamp(),
        ]);

        $signature = hash_hmac('sha256', $uri->getQuery()$this->secret);

        return new Request(
            'GET',
            $uri,
            [
                'shopware-app-signature' => $signature,
                'sw-version' => $this->shopwareVersion,
            ]
        );
    }

    

  public static function hmacBase64($data$key) {
    // $data and $key being strings here is necessary to avoid empty string     // results of the hash function if they are not scalar values. As this     // function is used in security-critical contexts like token validation it     // is important that it never returns an empty string.     if (!is_scalar($data) || !is_scalar($key)) {
      throw new \InvalidArgumentException('Both parameters passed to \Drupal\Component\Utility\Crypt::hmacBase64 must be scalar values.');
    }

    $hmac = base64_encode(hash_hmac('sha256', $data$key, TRUE));
    // Modify the hmac so it's safe to use in URLs.     return str_replace(['+', '/', '=']['-', '_', '']$hmac);
  }

  /** * Calculates a base-64 encoded, URL-safe sha-256 hash. * * @param string $data * String to be hashed. * * @return string * A base-64 encoded sha-256 hash, with + replaced with -, / with _ and * any = padding characters removed. */
static::assertArrayHasKey('sw-version', $signedQuery);
        static::assertEquals($this->getContainer()->getParameter('kernel.shopware_version')$signedQuery['sw-version']);

        static::assertArrayHasKey('sw-context-language', $signedQuery);
        static::assertEquals(Context::createDefaultContext()->getLanguageId()$signedQuery['sw-context-language']);

        static::assertArrayHasKey('sw-user-language', $signedQuery);
        static::assertEquals('en-GB', $signedQuery['sw-user-language']);

        static::assertArrayHasKey('shopware-shop-signature', $signedQuery);
        static::assertEquals(
            hash_hmac('sha256', Uri::withoutQueryValue($signedUri, 'shopware-shop-signature')->getQuery()$this->secret),
            $signedQuery['shopware-shop-signature']
        );
    }
}
Home | Imprint | This part of the site doesn't use cookies.