1 | <?php |
||
12 | class PEM |
||
13 | { |
||
14 | // well-known PEM types |
||
15 | const TYPE_CERTIFICATE = "CERTIFICATE"; |
||
16 | const TYPE_CRL = "X509 CRL"; |
||
17 | const TYPE_CERTIFICATE_REQUEST = "CERTIFICATE REQUEST"; |
||
18 | const TYPE_ATTRIBUTE_CERTIFICATE = "ATTRIBUTE CERTIFICATE"; |
||
19 | const TYPE_PRIVATE_KEY = "PRIVATE KEY"; |
||
20 | const TYPE_PUBLIC_KEY = "PUBLIC KEY"; |
||
21 | const TYPE_ENCRYPTED_PRIVATE_KEY = "ENCRYPTED PRIVATE KEY"; |
||
22 | const TYPE_RSA_PRIVATE_KEY = "RSA PRIVATE KEY"; |
||
23 | const TYPE_RSA_PUBLIC_KEY = "RSA PUBLIC KEY"; |
||
24 | const TYPE_EC_PRIVATE_KEY = "EC PRIVATE KEY"; |
||
25 | const TYPE_PKCS7 = "PKCS7"; |
||
26 | const TYPE_CMS = "CMS"; |
||
27 | |||
28 | /** |
||
29 | * Regular expression to match PEM block. |
||
30 | * |
||
31 | * @var string |
||
32 | */ |
||
33 | const PEM_REGEX = /* @formatter:off */ '/' . |
||
34 | /* line start */ '(?:^|[\r\n])' . |
||
35 | /* header */ '-----BEGIN (.+?)-----[\r\n]+' . |
||
36 | /* payload */ '(.+?)' . |
||
37 | /* trailer */ '[\r\n]+-----END \\1-----' . |
||
38 | '/ms'; /* @formatter:on */ |
||
39 | |||
40 | /** |
||
41 | * Content type. |
||
42 | * |
||
43 | * @var string $_type |
||
44 | */ |
||
45 | protected $_type; |
||
46 | |||
47 | /** |
||
48 | * Payload. |
||
49 | * |
||
50 | * @var string $_data |
||
51 | */ |
||
52 | protected $_data; |
||
53 | |||
54 | /** |
||
55 | * Constructor. |
||
56 | * |
||
57 | * @param string $type Content type |
||
58 | * @param string $data Payload |
||
59 | */ |
||
60 | public function __construct(string $type, string $data) |
||
65 | |||
66 | /** |
||
67 | * Initialize from a PEM-formatted string. |
||
68 | * |
||
69 | * @param string $str |
||
70 | * @throws \UnexpectedValueException If string is not valid PEM |
||
71 | * @return self |
||
72 | */ |
||
73 | public static function fromString(string $str): self |
||
85 | |||
86 | /** |
||
87 | * Initialize from a file. |
||
88 | * |
||
89 | * @param string $filename Path to file |
||
90 | * @throws \RuntimeException If file reading fails |
||
91 | * @return self |
||
92 | */ |
||
93 | public static function fromFile(string $filename): self |
||
101 | |||
102 | /** |
||
103 | * Get content type. |
||
104 | * |
||
105 | * @return string |
||
106 | */ |
||
107 | public function type(): string |
||
111 | |||
112 | /** |
||
113 | * Get payload. |
||
114 | * |
||
115 | * @return string |
||
116 | */ |
||
117 | public function data(): string |
||
121 | |||
122 | /** |
||
123 | * Encode to PEM string. |
||
124 | * |
||
125 | * @return string |
||
126 | */ |
||
127 | public function string(): string |
||
133 | |||
134 | /** |
||
135 | * |
||
136 | * @return string |
||
137 | */ |
||
138 | public function __toString() |
||
142 | } |
||
143 |