Passed
Branch signedelts (6bf033)
by Tim
04:10
created

Security::validateSignature()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 28
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 13
c 0
b 0
f 0
nc 6
nop 2
dl 0
loc 28
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XMLSecurity\Utils;
6
7
use SimpleSAML\XMLSecurity\Constants;
8
use SimpleSAML\XMLSecurity\Exception\InvalidArgumentException;
9
10
/**
11
 * A collection of security-related functions.
12
 *
13
 * @package simplesamlphp/xml-security
14
 */
15
class Security
16
{
17
    /**
18
     * Compare two strings in constant time.
19
     *
20
     * This function allows us to compare two given strings without any timing side channels
21
     * leaking information about them.
22
     *
23
     * @param string $known The reference string.
24
     * @param string $user The user-provided string to test.
25
     *
26
     * @return bool True if both strings are equal, false otherwise.
27
     */
28
    public static function compareStrings(string $known, string $user): bool
29
    {
30
        return hash_equals($known, $user);
31
    }
32
33
34
    /**
35
     * Compute the hash for some data with a given algorithm.
36
     *
37
     * @param string $alg The identifier of the algorithm to use.
38
     * @param string $data The data to digest.
39
     * @param bool $encode Whether to bas64-encode the result or not. Defaults to true.
40
     *
41
     * @return string The (binary or base64-encoded) digest corresponding to the given data.
42
     *
43
     * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $alg is not a valid
44
     *   identifier of a supported digest algorithm.
45
     */
46
    public static function hash(string $alg, string $data, bool $encode = true): string
47
    {
48
        if (!array_key_exists($alg, Constants::$DIGEST_ALGORITHMS)) {
49
            throw new InvalidArgumentException('Unsupported digest method "' . $alg . '"');
50
        }
51
52
        $digest = hash(Constants::$DIGEST_ALGORITHMS[$alg], $data, true);
53
        if ($encode) {
54
            $digest = base64_encode($digest);
55
        }
56
        return $digest;
57
    }
58
}
59