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
|
|
|
|