| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Webauthn\MetadataService\CertificateChain; |
| 6 |
|
| 7 |
use const PHP_EOL; |
| 8 |
|
| 9 |
final readonly class CertificateToolbox |
| 10 |
{ |
| 11 |
private const PEM_HEADER = '-----BEGIN '; |
| 12 |
|
| 13 |
private const PEM_FOOTER = '-----END '; |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
public static function fixPEMStructures(array $data, string $type = 'CERTIFICATE'): array |
| 21 |
{ |
| 22 |
return array_map(static fn ($d): string => self::fixPEMStructure($d, $type), $data); |
| 23 |
} |
| 24 |
|
| 25 |
public static function fixPEMStructure(string $data, string $type = 'CERTIFICATE'): string |
| 26 |
{ |
| 27 |
if (str_contains($data, self::PEM_HEADER)) { |
| 28 |
return trim($data); |
| 29 |
} |
| 30 |
$pem = self::PEM_HEADER . $type . '-----' . PHP_EOL; |
| 31 |
$pem .= chunk_split($data, 64, PHP_EOL); |
| 32 |
|
| 33 |
return $pem . (self::PEM_FOOTER . $type . '-----' . PHP_EOL); |
| 34 |
} |
| 35 |
|
| 36 |
public static function convertDERToPEM(string $data, string $type = 'CERTIFICATE'): string |
| 37 |
{ |
| 38 |
if (str_contains($data, self::PEM_HEADER)) { |
| 39 |
return $data; |
| 40 |
} |
| 41 |
|
| 42 |
return self::fixPEMStructure(base64_encode($data), $type); |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
public static function convertAllDERToPEM(array $data, string $type = 'CERTIFICATE'): array |
| 51 |
{ |
| 52 |
return array_map(static fn ($d): string => self::convertDERToPEM($d, $type), $data); |
| 53 |
} |
| 54 |
} |