Failed Conditions
Push — master ( 18441c...d72bf4 )
by Florent
83:08 queued 74:12
created

KeyConverter::loadKeyFromX509Resource()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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