Completed
Push — master ( 4df167...f708ed )
by Florent
02:36
created

KeyConverter::loadFromX5C()   C

Complexity

Conditions 7
Paths 4

Size

Total Lines 43
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 43
rs 6.7272
cc 7
eloc 33
nc 4
nop 1
1
<?php
2
3
/*
4
 * The MIT License (MIT)
5
 *
6
 * Copyright (c) 2014-2016 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
        throw new \InvalidArgumentException('Unable to load the certificate');
89
    }
90
91
    /**
92
     * @param string      $file
93
     * @param null|string $password
94
     *
95
     * @throws \Exception
96
     *
97
     * @return array
98
     */
99
    public static function loadFromKeyFile($file, $password = null)
100
    {
101
        $content = file_get_contents($file);
102
103
        return self::loadFromKey($content, $password);
104
    }
105
106
    /**
107
     * @param string      $key
108
     * @param null|string $password
109
     *
110
     * @throws \Exception
111
     *
112
     * @return array
113
     */
114
    public static function loadFromKey($key, $password = null)
115
    {
116
        try {
117
            return self::loadKeyFromDER($key, $password);
118
        } catch (\Exception $e) {
119
            return self::loadKeyFromPEM($key, $password);
120
        }
121
    }
122
123
    /**
124
     * @param string      $der
125
     * @param null|string $password
126
     *
127
     * @throws \Exception
128
     *
129
     * @return array
130
     */
131
    private static function loadKeyFromDER($der, $password = null)
132
    {
133
        $pem = self::convertDerToPem($der);
134
135
        return self::loadKeyFromPEM($pem, $password);
136
    }
137
138
    /**
139
     * @param string      $pem
140
     * @param null|string $password
141
     *
142
     * @throws \Exception
143
     *
144
     * @return array
145
     */
146
    private static function loadKeyFromPEM($pem, $password = null)
147
    {
148
        if (preg_match('#DEK-Info: (.+),(.+)#', $pem, $matches)) {
149
            $pem = self::decodePem($pem, $matches, $password);
150
        }
151
152
        $res = openssl_pkey_get_private($pem);
153
        if ($res === false) {
154
            $res = openssl_pkey_get_public($pem);
155
        }
156
        Assertion::false($res === false, 'Unable to load the key');
157
158
        $details = openssl_pkey_get_details($res);
159
        Assertion::isArray($details, 'Unable to get details of the key');
160
        Assertion::keyExists($details, 'type', 'Unable to get details of the key');
161
162
        switch ($details['type']) {
163
            case OPENSSL_KEYTYPE_EC:
164
                $ec_key = new ECKey($pem);
165
166
                return $ec_key->toArray();
167
            case OPENSSL_KEYTYPE_RSA:
168
                 $rsa_key = new RSAKey($pem);
169
170
                 return $rsa_key->toArray();
171
            default:
172
                throw new \InvalidArgumentException('Unsupported key type');
173
        }
174
    }
175
176
    /**
177
     * @param array $x5c
178
     *
179
     * @return array
180
     */
181
    public static function loadFromX5C(array $x5c)
182
    {
183
        $certificate = null;
184
        $last_issuer = null;
185
        $last_subject = null;
186
        foreach ($x5c as $cert) {
187
            $current_cert = '-----BEGIN CERTIFICATE-----'.PHP_EOL.$cert.PHP_EOL.'-----END CERTIFICATE-----';
188
            $x509 = openssl_x509_read($current_cert);
189
            if (false === $x509) {
190
                $last_issuer = null;
191
                $last_subject = null;
192
                break;
193
            }
194
            $parsed = openssl_x509_parse($x509);
195
196
            openssl_x509_free($x509);
197
            if (false === $parsed) {
198
                $last_issuer = null;
199
                $last_subject = null;
200
                break;
201
            }
202
            if (null === $last_subject) {
203
                $last_subject = $parsed['subject'];
204
                $last_issuer = $parsed['issuer'];
205
                $certificate = $current_cert;
206
            } else {
207
                if (json_encode($last_issuer) === json_encode($parsed['subject'])) {
208
                    $last_subject = $parsed['subject'];
209
                    $last_issuer = $parsed['issuer'];
210
                } else {
211
                    $last_issuer = null;
212
                    $last_subject = null;
213
                    break;
214
                }
215
            }
216
        }
217
        Assertion::false(
218
            null === $last_issuer || json_encode($last_issuer) !== json_encode($last_subject),
219
            'Invalid certificate chain.'
220
        );
221
222
        return self::loadKeyFromCertificate($certificate);
223
    }
224
225
    /**
226
     * @param string      $pem
227
     * @param string[]    $matches
228
     * @param null|string $password
229
     *
230
     * @return string
231
     */
232
    private static function decodePem($pem, array $matches, $password = null)
233
    {
234
        Assertion::notNull($password, 'Password required for encrypted keys.');
235
236
        $iv = pack('H*', trim($matches[2]));
237
        $iv_sub = mb_substr($iv, 0, 8, '8bit');
238
        $symkey = pack('H*', md5($password.$iv_sub));
239
        $symkey .= pack('H*', md5($symkey.$password.$iv_sub));
240
        $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $pem);
241
        $ciphertext = base64_decode(preg_replace('#-.*-|\r|\n#', '', $key));
242
243
        $decoded = openssl_decrypt($ciphertext, strtolower($matches[1]), $symkey, true, $iv);
244
245
        $number = preg_match_all('#-{5}.*-{5}#', $pem, $result);
246
        Assertion::eq($number, 2, 'Unable to load the key');
247
248
        $pem = $result[0][0].PHP_EOL;
249
        $pem .= chunk_split(base64_encode($decoded), 64);
250
        $pem .= $result[0][1].PHP_EOL;
251
252
        return $pem;
253
    }
254
255
    /**
256
     * @param string $der_data
257
     *
258
     * @return string
259
     */
260
    private static function convertDerToPem($der_data)
261
    {
262
        $pem = chunk_split(base64_encode($der_data), 64, PHP_EOL);
263
        $pem = '-----BEGIN CERTIFICATE-----'.PHP_EOL.$pem.'-----END CERTIFICATE-----'.PHP_EOL;
264
265
        return $pem;
266
    }
267
268
    /**
269
     * @param string $pem
270
     * @param string $algorithm
271
     * @param bool   $binary
272
     *
273
     * @return string
274
     */
275
    private static function calculateX509Fingerprint($pem, $algorithm, $binary = false)
276
    {
277
        $pem = preg_replace('#-.*-|\r|\n#', '', $pem);
278
        $bin = base64_decode($pem);
279
280
        return hash($algorithm, $bin, $binary);
281
    }
282
}
283