3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
13 * Tools for cryptography
18 * Compare two strings to avoid timing attacks
20 * C function memcmp() internally used by PHP, exits as soon as a difference
21 * is found in the two buffers. That makes possible of leaking
22 * timing information useful to an attacker attempting to iteratively guess
23 * the unknown string (e.g. password).
25 * @param string $expected
26 * @param string $actual
29 public static function compareStrings($expected, $actual)
31 $expected = (string) $expected;
32 $actual = (string) $actual;
33 $lenExpected = strlen($expected);
34 $lenActual = strlen($actual);
35 $len = min($lenExpected, $lenActual);
38 for ($i = 0; $i < $len; $i++
) {
39 $result |
= ord($expected[$i]) ^
ord($actual[$i]);
41 $result |
= $lenExpected ^
$lenActual;
43 return ($result === 0);