Passed
Pull Request — master (#77)
by Yuichi
04:41 queued 02:24
created

Pfx   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 21
c 2
b 0
f 0
dl 0
loc 69
ccs 0
cts 23
cp 0
rs 10
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A addExtracerts() 0 7 2
A pkcs12Read() 0 7 2
A read() 0 11 2
A toPem() 0 13 3
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
    public static function toPem($pfx, $password): string
18
    {
19
        $p12cert = array();
20
        $p12buf = self::read($pfx);
21
        $p12cert = self::pkcs12Read($p12buf, $p12cert, $password);
22
23
        if (empty($p12cert['cert']) || empty($p12cert['pkey'])) {
24
            throw new \RuntimeException('Cert file not include info.');
25
        }
26
27
        $pem = $p12cert['cert'] . "\n" . $p12cert['pkey'] . "\n";
28
29
        return self::addExtracerts($pem, $p12cert);
30
    }
31
32
    /**
33
     * @param $pfx
34
     * @return string
35
     * @throws \RuntimeException
36
     */
37
    private static function read($pfx): string
38
    {
39
        try {
40
            $fd = fopen($pfx, 'rb');
41
            $p12buf = fread($fd, filesize($pfx));
42
            fclose($fd);
43
        } catch (\Exception $e) {
44
            throw new \RuntimeException('Failed load cert file.');
45
        }
46
47
        return $p12buf;
48
    }
49
50
    /**
51
     * @param $p12buf
52
     * @param $p12cert
53
     * @param $password
54
     * @return array
55
     * @throws \RuntimeException
56
     */
57
    private static function pkcs12Read($p12buf, array $p12cert, $password): array
58
    {
59
        if (!openssl_pkcs12_read($p12buf, $p12cert, $password)) {
60
            throw new \RuntimeException('Invalid cert format or password.');
61
        }
62
63
        return $p12cert;
64
    }
65
66
    /**
67
     * @param $pem
68
     * @param $p12cert
69
     * @return string
70
     */
71
    private static function addExtracerts($pem, $p12cert): string
72
    {
73
        if (!empty($p12cert['extracerts'][0])) {
74
            $pem .= $p12cert['extracerts'][0];
75
        }
76
77
        return $pem;
78
    }
79
}
80