Passed
Push — master ( d0634e...13c37e )
by Yuichi
10:21 queued 22s
created

Pfx::addExtracerts()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 10
1
<?php
2
3
namespace CybozuHttp\Cert;
4
5
6
/**
7
 * @author ochi51 <[email protected]>
8
 */
9
class Pfx
10
{
11
    /**
12
     * @param $pfx
13
     * @param $password
14
     * @return string
15
     * @throws \RuntimeException
16
     */
17 1
    public static function toPem($pfx, $password): string
18
    {
19 1
        $p12cert = array();
20 1
        $p12buf = self::read($pfx);
21 1
        $p12cert = self::pkcs12Read($p12buf, $p12cert, $password);
22
23 1
        if (empty($p12cert['cert']) || empty($p12cert['pkey'])) {
24
            throw new \RuntimeException('Cert file not include info.');
25
        }
26
27 1
        $pem = $p12cert['cert'] . "\n" . $p12cert['pkey'] . "\n";
28
29 1
        return self::addExtracerts($pem, $p12cert);
30
    }
31
32
    /**
33
     * @param $pfx
34
     * @return string
35
     * @throws \RuntimeException
36
     */
37 1
    private static function read($pfx): string
38
    {
39
        try {
40 1
            $fd = fopen($pfx, 'rb');
41 1
            if ($fd === false) {
42 1
                throw new \RuntimeException('Failed load cert file.');
43
            }
44 1
            $p12buf = fread($fd, filesize($pfx));
45 1
            fclose($fd);
46 1
        } catch (\Exception $e) {
47 1
            throw new \RuntimeException('Failed load cert file.');
48
        }
49
50 1
        return $p12buf;
51
    }
52
53
    /**
54
     * @param $p12buf
55
     * @param $p12cert
56
     * @param $password
57
     * @return array
58
     * @throws \RuntimeException
59
     */
60 1
    private static function pkcs12Read($p12buf, array $p12cert, $password): array
61
    {
62 1
        if (!openssl_pkcs12_read($p12buf, $p12cert, $password)) {
63 1
            throw new \RuntimeException('Invalid cert format or password.');
64
        }
65
66 1
        return $p12cert;
67
    }
68
69
    /**
70
     * @param $pem
71
     * @param $p12cert
72
     * @return string
73
     */
74 1
    private static function addExtracerts($pem, $p12cert): string
75
    {
76 1
        if (!empty($p12cert['extracerts'][0])) {
77
            $pem .= $p12cert['extracerts'][0];
78
        }
79
80 1
        return $pem;
81
    }
82
}
83