-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathOpensslCipherKeyFactory.php
More file actions
65 lines (50 loc) · 1.7 KB
/
Copy pathOpensslCipherKeyFactory.php
File metadata and controls
65 lines (50 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
declare(strict_types=1);
namespace Patchlevel\Hydrator\Extension\Cryptography\Cipher;
use function function_exists;
use function in_array;
use function openssl_cipher_iv_length;
use function openssl_cipher_key_length;
use function openssl_get_cipher_methods;
use function openssl_random_pseudo_bytes;
final class OpensslCipherKeyFactory implements CipherKeyFactory
{
public const DEFAULT_METHOD = 'aes128';
private readonly int $keyLength;
private readonly int $ivLength;
/** @param non-empty-string $method */
public function __construct(
private readonly string $method = self::DEFAULT_METHOD,
) {
if (!self::methodSupported($this->method)) {
throw new MethodNotSupported($this->method);
}
$keyLength = 16;
if (function_exists('openssl_cipher_key_length')) {
$keyLength = @openssl_cipher_key_length($this->method);
}
$ivLength = @openssl_cipher_iv_length($this->method);
if ($keyLength === false || $ivLength === false) {
throw new MethodNotSupported($this->method);
}
$this->keyLength = $keyLength;
$this->ivLength = $ivLength;
}
public function __invoke(): CipherKey
{
return new CipherKey(
openssl_random_pseudo_bytes($this->keyLength),
$this->method,
openssl_random_pseudo_bytes($this->ivLength),
);
}
/** @return list<string> */
public static function supportedMethods(): array
{
return openssl_get_cipher_methods(true);
}
public static function methodSupported(string $method): bool
{
return in_array($method, self::supportedMethods(), true);
}
}