Utils   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 10
c 0
b 0
f 0
wmc 3
lcom 0
cbo 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A compareStrings() 0 21 3
1
<?php
2
/**
3
 * Copyright © 2017 Toan Nguyen. All rights reserved.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Gojira\Framework\Encryption;
10
11
/**
12
 * Tools for cryptography
13
 *
14
 * @package Gojira\Framework\Encryption
15
 * @author  Toan Nguyen <[email protected]>
16
 */
17
class Utils
18
{
19
    /**
20
     * Compare two strings to avoid timing attacks
21
     *
22
     * C function memcmp() internally used by PHP, exits as soon as a difference
23
     * is found in the two buffers. That makes possible of leaking
24
     * timing information useful to an attacker attempting to iteratively guess
25
     * the unknown string (e.g. password).
26
     * The length will leak.
27
     *
28
     * @param  string $expected
29
     * @param  string $actual
30
     *
31
     * @return bool
32
     */
33
    public static function compareStrings($expected, $actual)
34
    {
35
        $expected = (string)$expected;
36
        $actual = (string)$actual;
37
38
        if (function_exists('hash_equals')) {
39
            return hash_equals($expected, $actual);
40
        }
41
42
        $lenExpected = strlen($expected);
43
        $lenActual = strlen($actual);
44
        $len = min($lenExpected, $lenActual);
45
46
        $result = 0;
47
        for ($i = 0; $i < $len; $i++) {
48
            $result |= ord($expected[$i]) ^ ord($actual[$i]);
49
        }
50
        $result |= $lenExpected ^ $lenActual;
51
52
        return ($result === 0);
53
    }
54
}
55