Failed Conditions
Push — APNKeysSupport ( 79d3ae...1d99cc )
by Florent
03:38
created

src/KeyConverter/KeyConverter.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
        var_dump($pem);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($pem); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
153
        $res = openssl_pkey_get_private($pem);
154
        if ($res === false) {
155
            $res = openssl_pkey_get_public($pem);
156
        }
157
        Assertion::false($res === false, 'Unable to load the key');
158
159
        $details = openssl_pkey_get_details($res);
160
        Assertion::isArray($details, 'Unable to get details of the key');
161
        Assertion::keyExists($details, 'type', 'Unable to get details of the key');
162
163
        switch ($details['type']) {
164
            case OPENSSL_KEYTYPE_EC:
165
                $ec_key = new ECKey($pem);
166
167
                return $ec_key->toArray();
168
            case OPENSSL_KEYTYPE_RSA:
169
                 $rsa_key = new RSAKey($pem);
170
171
                 return $rsa_key->toArray();
172
            default:
173
                throw new \InvalidArgumentException('Unsupported key type');
174
        }
175
    }
176
177
    /**
178
     * @param array $x5c
179
     *
180
     * @return array
181
     */
182
    public static function loadFromX5C(array $x5c)
183
    {
184
        $certificate = null;
185
        $last_issuer = null;
186
        $last_subject = null;
187
        foreach ($x5c as $cert) {
188
            $current_cert = '-----BEGIN CERTIFICATE-----'.PHP_EOL.$cert.PHP_EOL.'-----END CERTIFICATE-----';
189
            $x509 = openssl_x509_read($current_cert);
190
            if (false === $x509) {
191
                $last_issuer = null;
192
                $last_subject = null;
193
                break;
194
            }
195
            $parsed = openssl_x509_parse($x509);
196
197
            openssl_x509_free($x509);
198
            if (false === $parsed) {
199
                $last_issuer = null;
200
                $last_subject = null;
201
                break;
202
            }
203
            if (null === $last_subject) {
204
                $last_subject = $parsed['subject'];
205
                $last_issuer = $parsed['issuer'];
206
                $certificate = $current_cert;
207
            } else {
208
                if (json_encode($last_issuer) === json_encode($parsed['subject'])) {
209
                    $last_subject = $parsed['subject'];
210
                    $last_issuer = $parsed['issuer'];
211
                } else {
212
                    $last_issuer = null;
213
                    $last_subject = null;
214
                    break;
215
                }
216
            }
217
        }
218
        Assertion::false(
219
            null === $last_issuer || json_encode($last_issuer) !== json_encode($last_subject),
220
            'Invalid certificate chain.'
221
        );
222
223
        return self::loadKeyFromCertificate($certificate);
224
    }
225
226
    /**
227
     * @param string      $pem
228
     * @param string[]    $matches
229
     * @param null|string $password
230
     *
231
     * @return string
232
     */
233
    private static function decodePem($pem, array $matches, $password = null)
234
    {
235
        Assertion::notNull($password, 'Password required for encrypted keys.');
236
237
        $iv = pack('H*', trim($matches[2]));
238
        $iv_sub = mb_substr($iv, 0, 8, '8bit');
239
        $symkey = pack('H*', md5($password.$iv_sub));
240
        $symkey .= pack('H*', md5($symkey.$password.$iv_sub));
241
        $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $pem);
242
        $ciphertext = base64_decode(preg_replace('#-.*-|\r|\n#', '', $key));
243
244
        $decoded = openssl_decrypt($ciphertext, strtolower($matches[1]), $symkey, true, $iv);
245
246
        $number = preg_match_all('#-{5}.*-{5}#', $pem, $result);
247
        Assertion::eq($number, 2, 'Unable to load the key');
248
249
        $pem = $result[0][0].PHP_EOL;
250
        $pem .= chunk_split(base64_encode($decoded), 64);
251
        $pem .= $result[0][1].PHP_EOL;
252
253
        return $pem;
254
    }
255
256
    /**
257
     * @param string $der_data
258
     *
259
     * @return string
260
     */
261
    private static function convertDerToPem($der_data)
262
    {
263
        $pem = chunk_split(base64_encode($der_data), 64, PHP_EOL);
264
        $pem = '-----BEGIN CERTIFICATE-----'.PHP_EOL.$pem.'-----END CERTIFICATE-----'.PHP_EOL;
265
266
        return $pem;
267
    }
268
269
    /**
270
     * @param string $pem
271
     * @param string $algorithm
272
     * @param bool   $binary
273
     *
274
     * @return string
275
     */
276
    private static function calculateX509Fingerprint($pem, $algorithm, $binary = false)
277
    {
278
        $pem = preg_replace('#-.*-|\r|\n#', '', $pem);
279
        $bin = base64_decode($pem);
280
281
        return hash($algorithm, $bin, $binary);
282
    }
283
}
284