Passed
Pull Request — master (#2)
by Jaime Pérez
02:11
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
use function count;
11
use function hash_equals;
12
use function in_array;
13
use function openssl_pkey_get_details;
14
use function serialize;
15
use function sha1;
16
use function str_pad;
17
use function str_replace;
18
use function strlen;
19
use function strval;
20
use function substr;
21
use function trim;
22
use function var_export;
23
24
/**
25
 * A collection of security-related functions.
26
 *
27
 * @package simplesamlphp/xml-security
28
 */
29
class Security
30
{
31
    /**
32
     * Compare two strings in constant time.
33
     *
34
     * This function allows us to compare two given strings without any timing side channels
35
     * leaking information about them.
36
     *
37
     * @param string $known The reference string.
38
     * @param string $user The user-provided string to test.
39
     *
40
     * @return bool True if both strings are equal, false otherwise.
41
     */
42
    public static function compareStrings(string $known, string $user): bool
43
    {
44
        return hash_equals($known, $user);
45
    }
46
47
48
    /**
49
     * Compute the hash for some data with a given algorithm.
50
     *
51
     * @param string $alg The identifier of the algorithm to use.
52
     * @param string $data The data to digest.
53
     * @param bool $encode Whether to bas64-encode the result or not. Defaults to true.
54
     *
55
     * @return string The (binary or base64-encoded) digest corresponding to the given data.
56
     *
57
     * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $alg is not a valid
58
     *   identifier of a supported digest algorithm.
59
     */
60
    public static function hash(string $alg, string $data, bool $encode = true): string
61
    {
62
        if (!array_key_exists($alg, Constants::$DIGEST_ALGORITHMS)) {
63
            throw new InvalidArgumentException('Unsupported digest method "' . $alg . '"');
64
        }
65
66
        $digest = hash(Constants::$DIGEST_ALGORITHMS[$alg], $data, true);
67
        if ($encode) {
68
            $digest = base64_encode($digest);
69
        }
70
        return $digest;
71
    }
72
}
73