Passed
Pull Request — master (#26)
by Jaime Pérez
02:00
created

Security::doDecryptElement()   C

Complexity

Conditions 17
Paths 97

Size

Total Lines 149
Code Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 71
dl 0
loc 149
rs 5.2166
c 1
b 0
f 0
cc 17
nc 97
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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