| Total Complexity | 9 |
| Total Lines | 69 |
| Duplicated Lines | 0 % |
| Coverage | 0% |
| Changes | 2 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 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 |
||
| 78 | } |
||
| 79 | } |
||
| 80 |