Failed Conditions
Push — v7 ( e9e51b...d9c0af )
by Florent
03:20
created

KeyConverter::loadKeyFromPEM()   C

Complexity

Conditions 8
Paths 20

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 21
nc 20
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2017 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace Jose\Component\KeyManagement\KeyConverter;
15
16
use Base64Url\Base64Url;
17
18
/**
19
 * This class will help you to load an EC key or a RSA key/certificate (private or public) and get values to create a JWK object.
20
 */
21
final class KeyConverter
22
{
23
    /**
24
     * @param string $file
25
     *
26
     * @throws \InvalidArgumentException
27
     *
28
     * @return array
29
     */
30
    public static function loadKeyFromCertificateFile(string $file): array
31
    {
32
        if (!file_exists($file)) {
33
            throw new \InvalidArgumentException(sprintf('File "%s" does not exist.', $file));
34
        }
35
        $content = file_get_contents($file);
36
37
        return self::loadKeyFromCertificate($content);
38
    }
39
40
    /**
41
     * @param string $certificate
42
     *
43
     * @throws \InvalidArgumentException
44
     *
45
     * @return array
46
     */
47
    public static function loadKeyFromCertificate(string $certificate): array
48
    {
49
        try {
50
            $res = openssl_x509_read($certificate);
51
        } catch (\Exception $e) {
52
            $certificate = self::convertDerToPem($certificate);
53
            $res = openssl_x509_read($certificate);
54
        }
55
        if (false === $res) {
56
            throw new \InvalidArgumentException('Unable to load the certificate.');
57
        }
58
59
        $values = self::loadKeyFromX509Resource($res);
60
        openssl_x509_free($res);
61
62
        return $values;
63
    }
64
65
    /**
66
     * @param resource $res
67
     *
68
     * @throws \Exception
69
     *
70
     * @return array
71
     */
72
    public static function loadKeyFromX509Resource($res): array
73
    {
74
        $key = openssl_get_publickey($res);
75
76
        $details = openssl_pkey_get_details($key);
77
        if (isset($details['key'])) {
78
            $values = self::loadKeyFromPEM($details['key']);
79
            openssl_x509_export($res, $out);
80
            $values['x5c'] = [trim(preg_replace('#-.*-#', '', $out))];
81
82
            if (function_exists('openssl_x509_fingerprint')) {
83
                $values['x5t'] = Base64Url::encode(openssl_x509_fingerprint($res, 'sha1', true));
84
                $values['x5t#256'] = Base64Url::encode(openssl_x509_fingerprint($res, 'sha256', true));
85
            } else {
86
                openssl_x509_export($res, $pem);
87
                $values['x5t'] = Base64Url::encode(self::calculateX509Fingerprint($pem, 'sha1', true));
88
                $values['x5t#256'] = Base64Url::encode(self::calculateX509Fingerprint($pem, 'sha256', true));
89
            }
90
91
            return $values;
92
        }
93
        throw new \InvalidArgumentException('Unable to load the certificate');
94
    }
95
96
    /**
97
     * @param string      $file
98
     * @param null|string $password
99
     *
100
     * @throws \Exception
101
     *
102
     * @return array
103
     */
104
    public static function loadFromKeyFile(string $file, ?string $password = null): array
105
    {
106
        $content = file_get_contents($file);
107
108
        return self::loadFromKey($content, $password);
109
    }
110
111
    /**
112
     * @param string      $key
113
     * @param null|string $password
114
     *
115
     * @throws \Exception
116
     *
117
     * @return array
118
     */
119
    public static function loadFromKey(string $key, ?string $password = null): array
120
    {
121
        try {
122
            return self::loadKeyFromDER($key, $password);
123
        } catch (\Exception $e) {
124
            return self::loadKeyFromPEM($key, $password);
125
        }
126
    }
127
128
    /**
129
     * @param string      $der
130
     * @param null|string $password
131
     *
132
     * @throws \Exception
133
     *
134
     * @return array
135
     */
136
    private static function loadKeyFromDER(string $der, ?string $password = null): array
137
    {
138
        $pem = self::convertDerToPem($der);
139
140
        return self::loadKeyFromPEM($pem, $password);
141
    }
142
143
    /**
144
     * @param string      $pem
145
     * @param null|string $password
146
     *
147
     * @throws \Exception
148
     *
149
     * @return array
150
     */
151
    private static function loadKeyFromPEM(string $pem, ?string $password = null): array
152
    {
153
        if (preg_match('#DEK-Info: (.+),(.+)#', $pem, $matches)) {
154
            $pem = self::decodePem($pem, $matches, $password);
155
        }
156
157
        self::sanitizePEM($pem);
158
159
        $res = openssl_pkey_get_private($pem);
160
        if ($res === false) {
161
            $res = openssl_pkey_get_public($pem);
162
        }
163
        if (false === $res) {
164
            throw new \InvalidArgumentException('Unable to load the key.');
165
        }
166
167
        $details = openssl_pkey_get_details($res);
168
        if (!is_array($details) || !array_key_exists('type', $details)) {
169
            throw new \InvalidArgumentException('Unable to get details of the key');
170
        }
171
172
        switch ($details['type']) {
173
            case OPENSSL_KEYTYPE_EC:
174
                $ec_key = ECKey::createFromPEM($pem);
175
176
                return $ec_key->toArray();
177
            case OPENSSL_KEYTYPE_RSA:
178
                 $rsa_key = RSAKey::createFromPEM($pem);
179
180
                 return $rsa_key->toArray();
181
            default:
182
                throw new \InvalidArgumentException('Unsupported key type');
183
        }
184
    }
185
186
    /**
187
     * This method modify the PEM to get 64 char lines and fix bug with old OpenSSL versions.
188
     *
189
     * @param string $pem
190
     */
191
    private static function sanitizePEM(string &$pem)
192
    {
193
        preg_match_all('#(-.*-)#', $pem, $matches, PREG_PATTERN_ORDER);
194
        $ciphertext = preg_replace('#-.*-|\r|\n| #', '', $pem);
195
196
        $pem = $matches[0][0].PHP_EOL;
197
        $pem .= chunk_split($ciphertext, 64, PHP_EOL);
198
        $pem .= $matches[0][1].PHP_EOL;
199
    }
200
201
    /**
202
     * @param array $x5c
203
     *
204
     * @return array
205
     */
206
    public static function loadFromX5C(array $x5c): array
207
    {
208
        $certificate = null;
209
        $last_issuer = null;
210
        $last_subject = null;
211
        foreach ($x5c as $cert) {
212
            $current_cert = '-----BEGIN CERTIFICATE-----'.PHP_EOL.$cert.PHP_EOL.'-----END CERTIFICATE-----';
213
            $x509 = openssl_x509_read($current_cert);
214
            if (false === $x509) {
215
                $last_issuer = null;
216
                $last_subject = null;
217
                break;
218
            }
219
            $parsed = openssl_x509_parse($x509);
220
221
            openssl_x509_free($x509);
222
            if (false === $parsed) {
223
                $last_issuer = null;
224
                $last_subject = null;
225
                break;
226
            }
227
            if (null === $last_subject) {
228
                $last_subject = $parsed['subject'];
229
                $last_issuer = $parsed['issuer'];
230
                $certificate = $current_cert;
231
            } else {
232
                if (json_encode($last_issuer) === json_encode($parsed['subject'])) {
233
                    $last_subject = $parsed['subject'];
234
                    $last_issuer = $parsed['issuer'];
235
                } else {
236
                    $last_issuer = null;
237
                    $last_subject = null;
238
                    break;
239
                }
240
            }
241
        }
242
        if (null !== $last_issuer && json_encode($last_issuer) !== json_encode($last_subject)) {
243
            throw new \InvalidArgumentException('Invalid certificate chain.');
244
        }
245
246
        return self::loadKeyFromCertificate($certificate);
247
    }
248
249
    /**
250
     * @param string      $pem
251
     * @param string[]    $matches
252
     * @param null|string $password
253
     *
254
     * @return string
255
     */
256
    private static function decodePem(string $pem, array $matches, ?string $password = null): string
257
    {
258
        if (null === $password) {
259
            throw new \InvalidArgumentException('Password required for encrypted keys.');
260
        }
261
262
        $iv = pack('H*', trim($matches[2]));
263
        $iv_sub = mb_substr($iv, 0, 8, '8bit');
264
        $symkey = pack('H*', md5($password.$iv_sub));
265
        $symkey .= pack('H*', md5($symkey.$password.$iv_sub));
266
        $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $pem);
267
        $ciphertext = base64_decode(preg_replace('#-.*-|\r|\n#', '', $key));
268
269
        $decoded = openssl_decrypt($ciphertext, strtolower($matches[1]), $symkey, OPENSSL_RAW_DATA, $iv);
270
271
        $number = preg_match_all('#-{5}.*-{5}#', $pem, $result);
272
        if (2 !== $number) {
273
            throw new \InvalidArgumentException('Unable to load the key');
274
        }
275
276
        $pem = $result[0][0].PHP_EOL;
277
        $pem .= chunk_split(base64_encode($decoded), 64);
278
        $pem .= $result[0][1].PHP_EOL;
279
280
        return $pem;
281
    }
282
283
    /**
284
     * @param string $der_data
285
     *
286
     * @return string
287
     */
288
    private static function convertDerToPem(string $der_data): string
289
    {
290
        $pem = chunk_split(base64_encode($der_data), 64, PHP_EOL);
291
        $pem = '-----BEGIN CERTIFICATE-----'.PHP_EOL.$pem.'-----END CERTIFICATE-----'.PHP_EOL;
292
293
        return $pem;
294
    }
295
296
    /**
297
     * @param string $pem
298
     * @param string $algorithm
299
     * @param bool   $binary
300
     *
301
     * @return string
302
     */
303
    private static function calculateX509Fingerprint(string $pem, string $algorithm, bool $binary = false): string
304
    {
305
        $pem = preg_replace('#-.*-|\r|\n#', '', $pem);
306
        $bin = base64_decode($pem);
307
308
        return hash($algorithm, $bin, $binary);
309
    }
310
}
311