Completed
Push — master ( a826f8...312899 )
by Yuichi
25s
created

Pfx::addExtracerts()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 3
cts 4
cp 0.75
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2.0625
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
            $p12buf = fread($fd, filesize($pfx));
42 1
            fclose($fd);
43 1
        } catch (\Exception $e) {
44 1
            throw new \RuntimeException('Failed load cert file.');
45
        }
46
47 1
        return $p12buf;
48
    }
49
50
    /**
51
     * @param $p12buf
52
     * @param $p12cert
53
     * @param $password
54
     * @return array
55
     * @throws \RuntimeException
56
     */
57 1
    private static function pkcs12Read($p12buf, array $p12cert, $password): array
58
    {
59 1
        if (!openssl_pkcs12_read($p12buf, $p12cert, $password)) {
60 1
            throw new \RuntimeException('Invalid cert format or password.');
61
        }
62
63 1
        return $p12cert;
64
    }
65
66
    /**
67
     * @param $pem
68
     * @param $p12cert
69
     * @return string
70
     */
71 1
    private static function addExtracerts($pem, $p12cert): string
72
    {
73 1
        if (!empty($p12cert['extracerts'][0])) {
74
            $pem .= $p12cert['extracerts'][0];
75
        }
76
77 1
        return $pem;
78
    }
79
}
80