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