hash_equals

Timing attack safe string comparison.

Description

hash_equals( (string) $a, (string) $b ); 

Compares two strings using the same time whether they're equal or not.

This function was added in PHP 5.6.

Note: It can leak the length of a string when arguments of differing length are supplied.

Parameters (2)

0. $a (string)
Expected string.
1. $b (string)
Actual, user supplied, string.

Usage

  1. if ( !function_exists( 'hash_equals' ) ) { 
  2. require_once ABSPATH . WPINC . '/compat.php'; 
  3.  
  4. // Expected string. 
  5. $a = ''; 
  6.  
  7. // Actual, user supplied, string. 
  8. $b = ''; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = hash_equals($a, $b); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/compat.php  
  1. function hash_equals( $a, $b ) { 
  2. $a_length = strlen( $a ); 
  3. if ( $a_length !== strlen( $b ) ) { 
  4. return false; 
  5. $result = 0; 
  6.  
  7. // Do not attempt to "optimize" this. 
  8. for ( $i = 0; $i < $a_length; $i++ ) { 
  9. $result |= ord( $a[ $i ] ) ^ ord( $b[ $i ] ); 
  10.  
  11. return $result === 0;