EncryptionAlgorithmFactory::__construct()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 18
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 7
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 18
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XMLSecurity\Alg\Encryption;
6
7
use SimpleSAML\Assert\Assert;
8
use SimpleSAML\XMLSecurity\Constants as C;
9
use SimpleSAML\XMLSecurity\Exception\BlacklistedAlgorithmException;
10
use SimpleSAML\XMLSecurity\Exception\UnsupportedAlgorithmException;
11
use SimpleSAML\XMLSecurity\Key\KeyInterface;
12
13
use function array_key_exists;
14
use function sprintf;
15
16
/**
17
 * Factory class to create and configure encryption algorithms.
18
 *
19
 * @package simplesamlphp/xml-security
20
 */
21
final class EncryptionAlgorithmFactory
22
{
23
    /**
24
     * An array of blacklisted algorithms.
25
     *
26
     * Defaults to 3DES.
27
     *
28
     * @var string[]
29
     */
30
    public const DEFAULT_BLACKLIST = [
31
        C::BLOCK_ENC_3DES,
32
    ];
33
34
    /**
35
     * An array of default algorithms that can be used.
36
     *
37
     * @var class-string[]
38
     */
39
    private const SUPPORTED_DEFAULTS = [
40
        TripleDES::class,
41
        AES::class,
42
    ];
43
44
45
    /**
46
     * A cache of algorithm implementations indexed by algorithm ID.
47
     *
48
     * @var array<string, \SimpleSAML\XMLSecurity\Alg\Encryption\EncryptionAlgorithmInterface>
49
     */
50
    protected static array $cache = [];
51
52
    /**
53
     * Whether the factory has been initialized or not.
54
     *
55
     * @var bool
56
     */
57
    protected static bool $initialized = false;
58
59
60
    /**
61
     * Build a factory that creates algorithms.
62
     *
63
     * @param string[] $blacklist A list of algorithms forbidden for their use.
64
     */
65
    public function __construct(
66
        protected array $blacklist = self::DEFAULT_BLACKLIST,
67
    ) {
68
        // initialize the cache for supported algorithms per known implementation
69
        if (!self::$initialized) {
70
            foreach (self::SUPPORTED_DEFAULTS as $algorithm) {
71
                foreach ($algorithm::getSupportedAlgorithms() as $algId) {
72
                    if (array_key_exists($algId, self::$cache) && !array_key_exists($algId, $this->blacklist)) {
73
                        /*
74
                         * If the key existed before initialization, that means someone registered a handler for this
75
                         * algorithm, so we should respect that and skip registering the default here.
76
                         */
77
                        continue;
78
                    }
79
                    self::$cache[$algId] = $algorithm;
80
                }
81
            }
82
            self::$initialized = true;
83
        }
84
    }
85
86
87
    /**
88
     * Get a new object implementing the given digital signature algorithm.
89
     *
90
     * @param string $algId The identifier of the algorithm desired.
91
     * @param \SimpleSAML\XMLSecurity\Key\KeyInterface $key The key to use with the given algorithm.
92
     *
93
     * @return \SimpleSAML\XMLSecurity\Alg\Encryption\EncryptionAlgorithmInterface An object implementing the given
94
     * algorithm.
95
     *
96
     * @throws \SimpleSAML\XMLSecurity\Exception\UnsupportedAlgorithmException If an error occurs, e.g. the given
97
     * algorithm is blacklisted, unknown or the given key is not suitable for it.
98
     */
99
    public function getAlgorithm(
100
        string $algId,
101
        #[\SensitiveParameter]
102
        KeyInterface $key,
103
    ): EncryptionAlgorithmInterface {
104
        Assert::notInArray(
105
            $algId,
106
            $this->blacklist,
107
            sprintf('Blacklisted algorithm: \'%s\'.', $algId),
108
            BlacklistedAlgorithmException::class,
109
        );
110
        Assert::keyExists(
111
            self::$cache,
112
            $algId,
113
            sprintf('Unknown or unsupported algorithm: \'%s\'.', $algId),
114
            UnsupportedAlgorithmException::class,
115
        );
116
117
        return new self::$cache[$algId]($key, $algId);
118
    }
119
120
121
    /**
122
     * Register an implementation of some algorithm(s) for its use.
123
     *
124
     * @param class-string $className
125
     */
126
    public static function registerAlgorithm(string $className): void
127
    {
128
        Assert::implementsInterface(
129
            $className,
130
            EncryptionAlgorithmInterface::class,
131
            sprintf(
132
                'Cannot register algorithm "%s", must implement %s.',
133
                $className,
134
                EncryptionAlgorithmInterface::class,
135
            ),
136
        );
137
138
        foreach ($className::getSupportedAlgorithms() as $algId) {
139
            self::$cache[$algId] = $className;
140
        }
141
    }
142
}
143