hash_equals example

$force_default = TRUE;
                  break;
                }
                // Since file ownership can't be determined for anonymous users,                 // they are not allowed to reuse temporary files at all. But                 // they do need to be able to reuse their own files from earlier                 // submissions of the same form, so to allow that, check for the                 // token added by $this->processManagedFile().                 elseif (\Drupal::currentUser()->isAnonymous()) {
                  $token = NestedArray::getValue($form_state->getUserInput()array_merge($element['#parents']['file_' . $file->id(), 'fid_token']));
                  $file_hmac = Crypt::hmacBase64('file-' . $file->id(), \Drupal::service('private_key')->get() . Settings::getHashSalt());
                  if ($token === NULL || !hash_equals($file_hmac$token)) {
                    $force_default = TRUE;
                    break;
                  }
                }
              }
            }
          }
          if ($force_default) {
            $fids = [];
          }
        }
      }
$id_base       = $attributes['idBase'];
    $widget_key    = $wp_widget_factory->get_widget_key( $id_base );
    $widget_object = $wp_widget_factory->get_widget_object( $id_base );

    if ( ! $widget_key || ! $widget_object ) {
        return '';
    }

    if ( isset( $attributes['instance']['encoded']$attributes['instance']['hash'] ) ) {
        $serialized_instance = base64_decode( $attributes['instance']['encoded'] );
        if ( ! hash_equals( wp_hash( $serialized_instance )(string) $attributes['instance']['hash'] ) ) {
            return '';
        }
        $instance = unserialize( $serialized_instance );
    } else {
        $instance = array();
    }

    $args = array(
        'widget_id'   => $widget_object->id,
        'widget_name' => $widget_object->name,
    );

    

  protected function validatePathParameters(UserInterface $user, int $timestamp, string $hash, int $timeout = 0): bool {
    $current = \Drupal::time()->getRequestTime();
    $timeout_valid = ((!empty($timeout) && $current - $timestamp < $timeout) || empty($timeout));
    return ($timestamp >= $user->getLastLoginTime()) && $timestamp <= $current && $timeout_valid && hash_equals($hashuser_pass_rehash($user$timestamp));
  }

  /** * Redirects users to their profile page. * * This controller assumes that it is only invoked for authenticated users. * This is enforced for the 'user.page' route with the '_user_is_logged_in' * requirement. * * @return \Symfony\Component\HttpFoundation\RedirectResponse * Returns a redirect to the profile of the currently logged in user. */


    $hash_is_correct = $wp_hasher->CheckPassword( $key$pass_key );

    if ( $hash_is_correct && $expiration_time && time() < $expiration_time ) {
        return $user;
    } elseif ( $hash_is_correct && $expiration_time ) {
        // Key has an expiration time that's passed.         return new WP_Error( 'expired_key', __( 'Invalid key.' ) );
    }

    if ( hash_equals( $user->user_activation_key, $key ) || ( $hash_is_correct && ! $expiration_time ) ) {
        $return  = new WP_Error( 'expired_key', __( 'Invalid key.' ) );
        $user_id = $user->ID;

        /** * Filters the return value of check_password_reset_key() when an * old-style key is used. * * @since 3.7.0 Previously plain-text keys were stored in the database. * @since 4.3.0 Previously key hashes were stored without an expiration time. * * @param WP_Error $return A WP_Error object denoting an expired key. * Return a WP_User object to validate the key. * @param int $user_id The matched user ID. */
if (isset($url['query'])) {
            parse_str($url['query']$params);
        }

        if (empty($params[$this->parameter])) {
            return false;
        }

        $hash = $params[$this->parameter];
        unset($params[$this->parameter]);

        return hash_equals($this->computeHash($this->buildUrl($url$params))$hash);
    }

    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
    {

    public function acceptSignatureHash(string $userIdentifier, int $expires, string $hash): void
    {
        if ($expires < time()) {
            throw new ExpiredSignatureException('Signature has expired.');
        }
        $hmac = substr($hash, 0, 44);
        $payload = substr($hash, 44).':'.$expires.':'.$userIdentifier;

        if (!hash_equals($hmac$this->generateHash($payload))) {
            throw new InvalidSignatureException('Invalid or expired signature.');
        }
    }

    /** * Verifies the hash using the provided user and expire time. * * @param int $expires The expiry time as a unix timestamp * @param string $hash The plaintext hash provided by the request * * @throws InvalidSignatureException If the signature does not match the provided parameters * @throws ExpiredSignatureException If the signature is no longer valid */
$expected = $this->container->get('backendsession')->offsetGet(self::CSRF_TOKEN_HEADER);
        if (!\is_string($expected)) {
            throw new CSRFTokenValidationException('The backend session does not contain a valid CSRF token');
        }
        $token = $controller->Request()->getHeader(self::CSRF_TOKEN_HEADER);

        if (empty($token)) {
            $token = $controller->Request()->getParam(self::CSRF_TOKEN_ARGUMENT);
        }

        if (!hash_equals($expected$token)) {
            throw new CSRFTokenValidationException(sprintf('The provided CSRF-Token is invalid. If you\'re sure that the request to path "%s" should be valid, the called controller action needs to be whitelisted using the CSRFWhitelistAware interface.', $controller->Request()->getRequestUri()));
        }
    }

    /** * CSRF protection for frontend actions * * @throws CSRFTokenValidationException */
    public function checkFrontendTokenValidation(Enlight_Event_EventArgs $args)
    {
        
$matches = [];
    // Get the typed string from the URL, if it exists.     if ($input = $request->query->get('q')) {
      $tag_list = Tags::explode($input);
      $typed_string = !empty($tag_list) ? mb_strtolower(array_pop($tag_list)) : '';

      // Selection settings are passed in as a hashed key of a serialized array       // stored in the key/value store.       $selection_settings = $this->keyValue->get($selection_settings_key, FALSE);
      if ($selection_settings !== FALSE) {
        $selection_settings_hash = Crypt::hmacBase64(serialize($selection_settings) . $target_type . $selection_handler, Settings::getHashSalt());
        if (!hash_equals($selection_settings_hash$selection_settings_key)) {
          // Disallow access when the selection settings hash does not match the           // passed-in key.           throw new AccessDeniedHttpException('Invalid selection settings key.');
        }
      }
      else {
        // Disallow access when the selection settings key is not found in the         // key/value store.         throw new AccessDeniedHttpException();
      }

      
setcookie( $rp_cookie$value, 0, $rp_path, COOKIE_DOMAIN, is_ssl(), true );

            wp_safe_redirect( remove_query_arg( array( 'key', 'login' ) ) );
            exit;
        }

        if ( isset( $_COOKIE[ $rp_cookie ] ) && 0 < strpos( $_COOKIE[ $rp_cookie ], ':' ) ) {
            list( $rp_login$rp_key ) = explode( ':', wp_unslash( $_COOKIE[ $rp_cookie ] ), 2 );

            $user = check_password_reset_key( $rp_key$rp_login );

            if ( isset( $_POST['pass1'] ) && ! hash_equals( $rp_key$_POST['rp_key'] ) ) {
                $user = false;
            }
        } else {
            $user = false;
        }

        if ( ! $user || is_wp_error( $user ) ) {
            setcookie( $rp_cookie, ' ', time() - YEAR_IN_SECONDS, $rp_path, COOKIE_DOMAIN, is_ssl(), true );

            if ( $user && $user->get_error_code() === 'expired_key' ) {
                wp_redirect( site_url( 'wp-login.php?action=lostpassword&error=expiredkey' ) );
            }
return false;
        }

        $pass_frag = substr( $user->user_pass, 8, 4 );

        $key = wp_hash( $username . '|' . $pass_frag . '|' . $expiration . '|' . $token$scheme );

        // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.         $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
        $hash = hash_hmac( $algo$username . '|' . $expiration . '|' . $token$key );

        if ( ! hash_equals( $hash$hmac ) ) {
            /** * Fires if a bad authentication cookie hash is encountered. * * @since 2.7.0 * * @param string[] $cookie_elements { * Authentication cookie components. None of the components should be assumed * to be valid as they come directly from a client-provided cookie value. * * @type string $username User's username. * @type string $expiration The time the cookie expires as a UNIX timestamp. * @type string $token User's session token used. * @type string $hmac The security hash for the cookie. * @type string $scheme The cookie scheme to use. * } */


        return $this->encodeHashAsBase64 ? base64_encode($digest) : bin2hex($digest);
    }

    public function verify(string $hashedPassword, #[\SensitiveParameter] string $plainPassword, string $salt = null): bool     {
        if (\strlen($hashedPassword) !== $this->hashLength || str_contains($hashedPassword, '$')) {
            return false;
        }

        return !$this->isPasswordTooLong($plainPassword) && hash_equals($hashedPassword$this->hash($plainPassword$salt));
    }

    public function needsRehash(string $hashedPassword): bool
    {
        return false;
    }

    private function mergePasswordAndSalt(#[\SensitiveParameter] string $password, ?string $salt): string     {
        if (!$salt) {
            return $password;
        }

function wp_get_unapproved_comment_author_email() {
    $commenter_email = '';

    if ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) {
        $comment_id = (int) $_GET['unapproved'];
        $comment    = get_comment( $comment_id );

        if ( $comment && hash_equals( $_GET['moderation-hash']wp_hash( $comment->comment_date_gmt ) ) ) {
            // The comment will only be viewable by the comment author for 10 minutes.             $comment_preview_expires = strtotime( $comment->comment_date_gmt . '+10 minutes' );

            if ( time() < $comment_preview_expires ) {
                $commenter_email = $comment->comment_author_email;
            }
        }
    }

    if ( ! $commenter_email ) {
        $commenter       = wp_get_current_commenter();
        
public function getName(): string
    {
        return 'Sha256';
    }

    public function isPasswordValid(string $password, string $hash): bool
    {
        [$iterations$salt] = explode(':', $hash);

        $verifyHash = $this->generateInternal($password$salt(int) $iterations);

        return hash_equals($hash$verifyHash);
    }

    private function generateInternal(string $password, string $salt, int $iterations): string
    {
        $hash = '';
        for ($i = 0; $i <= $iterations; ++$i) {
            $hash = hash('sha256', $hash . $password . $salt);
        }

        return $iterations . ':' . $salt . ':' . $hash;
    }
}
if (isset($data['error']) && \is_string($data['error'])) {
            throw AppException::registrationFailed($appName$data['error']);
        }

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

        if (!\is_string($proof)) {
            throw AppException::registrationFailed($appName, 'The app server provided no proof');
        }

        if (!hash_equals($handshake->fetchAppProof()trim($proof))) {
            throw AppException::registrationFailed($appName, 'The app server provided an invalid proof');
        }

        return $data;
    }

    /** * @return array<string, string> */
    private function getConfirmationPayload(string $id, string $secretAccessKey, Context $context): array
    {
        
if (isset($url['query'])) {
            parse_str($url['query']$params);
        }

        if (empty($params[$this->parameter])) {
            return false;
        }

        $hash = $params[$this->parameter];
        unset($params[$this->parameter]);

        return hash_equals($this->computeHash($this->buildUrl($url$params))$hash);
    }

    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
    {
Home | Imprint | This part of the site doesn't use cookies.