Completed
Push — master ( 26ae43...5f93f7 )
by Florent
10:44 queued 10:44
created

X5CFinder::converX5CToJWK()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 1
Metric Value
c 2
b 2
f 1
dl 0
loc 20
rs 8.8571
cc 5
eloc 12
nc 4
nop 1
1
<?php
2
3
/*
4
 * The MIT License (MIT)
5
 *
6
 * Copyright (c) 2014-2015 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\Finder;
13
14
use Jose\KeyConverter\KeyConverter;
15
16
/**
17
 */
18
class X5CFinder implements JWKFinderInterface
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23
    public function findJWK(array $header)
24
    {
25
        if (!isset($header['x5c'])) {
26
            return;
27
        }
28
        if (is_array($header['x5c'])) {
29
            return $this->loadX5CCertificateChain($header['x5c']);
30
        } else {
31
            return;
32
        }
33
    }
34
35
    /**
36
     * @param array $chain
37
     *
38
     * @return array|null
39
     */
40
    protected function loadX5CCertificateChain(array $chain)
41
    {
42
        $certificate = null;
43
        $last_issuer = null;
44
        $last_subject = null;
45
        foreach ($chain as $cert) {
46
            $current_cert = "-----BEGIN CERTIFICATE-----\n$cert\n-----END CERTIFICATE-----";
47
            $x509 = openssl_x509_read($current_cert);
48
            if (false === $x509) {
49
                $last_issuer = null;
50
                $last_subject = null;
51
                break;
52
            }
53
            $parsed = openssl_x509_parse($x509);
54
            openssl_x509_free($x509);
55
            if (false === $parsed) {
56
                $last_issuer = null;
57
                $last_subject = null;
58
                break;
59
            }
60
            if (null === $last_subject) {
61
                $last_subject = $parsed['subject'];
62
                $last_issuer = $parsed['issuer'];
63
                $certificate = $current_cert;
64
            } else {
65
                if (json_encode($last_issuer) === json_encode($parsed['subject'])) {
66
                    $last_subject = $parsed['subject'];
67
                    $last_issuer = $parsed['issuer'];
68
                } else {
69
                    $last_issuer = null;
70
                    $last_subject = null;
71
                    break;
72
                }
73
            }
74
        }
75
        if (null === $last_issuer || json_encode($last_issuer) !== json_encode($last_subject)) {
76
            return;
77
        }
78
79
        return KeyConverter::loadKeyFromCertificate($certificate);
80
    }
81
}
82