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