Passed
Push — master ( d55ec2...1839a8 )
by Rogier
11:41
created

OpenSsl::openSslKeyToString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Rogierw\RwAcme\Support;
4
5
use OpenSSLAsymmetricKey;
6
use RuntimeException;
7
8
class OpenSsl
9
{
10
    public static function generatePrivateKey(): OpenSSLAsymmetricKey
11
    {
12
        return openssl_pkey_new([
13
            'private_key_bits' => 2048,
14
            'digest_alg'       => 'sha256',
15
        ]);
16
    }
17
18
    public static function openSslKeyToString(OpenSSLAsymmetricKey $key): string
19
    {
20
        if (!openssl_pkey_export($key, $output)) {
21
            throw new RuntimeException('Exporting SSL key failed.');
22
        }
23
24
        return trim($output);
25
    }
26
27
    public static function generateCsr(array $domains, OpenSSLAsymmetricKey $privateKey): string
28
    {
29
        $dn = ['commonName' => $domains[0]];
30
31
        $san = implode(',', array_map(function ($dns) {
32
            return 'DNS:' . $dns;
33
        }, $domains));
34
35
        $tempFile = tmpfile();
36
37
        fwrite(
38
            $tempFile,
39
            'HOME = .
40
			RANDFILE = $ENV::HOME/.rnd
41
			[ req ]
42
			default_bits = 4096
43
			default_keyfile = privkey.pem
44
			distinguished_name = req_distinguished_name
45
			req_extensions = v3_req
46
			[ req_distinguished_name ]
47
			countryName = Country Name (2 letter code)
48
			[ v3_req ]
49
			basicConstraints = CA:FALSE
50
			subjectAltName = ' . $san . '
51
			keyUsage = nonRepudiation, digitalSignature, keyEncipherment'
52
        );
53
54
        $csr = openssl_csr_new($dn, $privateKey, [
55
            'digest_alg' => 'sha256',
56
            'config'     => stream_get_meta_data($tempFile)['uri'],
57
        ]);
58
59
        fclose($tempFile);
60
61
        if (!openssl_csr_export($csr, $out)) {
62
            throw new RuntimeException('Exporting CSR failed.');
63
        }
64
65
        return trim($out);
66
    }
67
}
68