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
|
|
|
|