KeyGenerator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 23
dl 0
loc 58
ccs 0
cts 20
cp 0
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A EC() 0 21 4
A RSA() 0 18 3
1
<?php
2
3
namespace LE_ACME2\Utilities;
4
5
class KeyGenerator {
6
7
    /**
8
     * Generates a new RSA keypair and saves both keys to a new file.
9
     *
10
     * @param string	$directory		The directory in which to store the new keys.
11
     * @param string	$privateKeyFile	The filename for the private key file.
12
     * @param string	$publicKeyFile  The filename for the public key file.
13
     */
14
    public static function RSA(string $directory, string $privateKeyFile = 'private.pem', string $publicKeyFile = 'public.pem') {
15
16
        $res = openssl_pkey_new([
17
            "private_key_type" => OPENSSL_KEYTYPE_RSA,
18
            "private_key_bits" => 4096,
19
        ]);
20
21
        if(!openssl_pkey_export($res, $privateKey))
22
            throw new \RuntimeException("RSA keypair export failed!");
23
24
        $details = openssl_pkey_get_details($res);
25
26
        file_put_contents($directory . $privateKeyFile, $privateKey);
27
        file_put_contents($directory . $publicKeyFile, $details['key']);
28
29
        if(PHP_MAJOR_VERSION < 8) {
30
            // deprecated after PHP 8.0.0 and not needed anymore
31
            openssl_pkey_free($res);
32
        }
33
    }
34
35
    /**
36
     * Generates a new EC prime256v1 keypair and saves both keys to a new file.
37
     *
38
     * @param string	$directory		The directory in which to store the new keys.
39
     * @param string	$privateKeyFile	The filename for the private key file.
40
     * @param string	$publicKeyFile  The filename for the public key file.
41
     */
42
    public static function EC(string $directory, string $privateKeyFile = 'private.pem', string $publicKeyFile = 'public.pem') {
43
44
        if (version_compare(PHP_VERSION, '7.1.0') == -1)
45
            throw new \RuntimeException("PHP 7.1+ required for EC keys");
46
47
        $res = openssl_pkey_new([
48
            "private_key_type" => OPENSSL_KEYTYPE_EC,
49
            "curve_name" => "prime256v1",
50
        ]);
51
52
        if(!openssl_pkey_export($res, $privateKey))
53
            throw new \RuntimeException("EC keypair export failed!");
54
55
        $details = openssl_pkey_get_details($res);
56
57
        file_put_contents($directory . $privateKeyFile, $privateKey);
58
        file_put_contents($directory . $publicKeyFile, $details['key']);
59
60
        if(PHP_MAJOR_VERSION < 8) {
61
            // deprecated after PHP 8.0.0 and not needed anymore
62
            openssl_pkey_free($res);
63
        }
64
    }
65
}