string(); } public static function create(string $_type, string $_data): self { return new self($_type, $_data); } /** * Initialize from a PEM-formatted string. */ public static function fromString(string $str): self { $result = preg_match(self::PEM_REGEX, $str, $match); if ($result === false) { // a matcher that gave up says nothing about the input, so it must not be reported as malformed throw new RuntimeException('Failed to match a PEM block: ' . preg_last_error_msg() . '.'); } if ($result !== 1) { throw new UnexpectedValueException('Not a PEM formatted string.'); } $payload = preg_replace('/\s+/', '', $match[2]); if (! is_string($payload)) { throw new UnexpectedValueException('Failed to decode PEM data.'); } // base64_decode() is strict about the alphabet but not about padding, so a blob that OpenSSL refuses // would otherwise be accepted here (RFC 7468 sect. 3 requires the padded alphabet of RFC 4648) if (mb_strlen($payload, '8bit') % 4 !== 0) { throw new UnexpectedValueException('Failed to decode PEM data.'); } $data = base64_decode($payload, true); if ($data === false) { throw new UnexpectedValueException('Failed to decode PEM data.'); } return self::create($match[1], $data); } /** * Initialize from a file. * * @param string $filename Path to file */ public static function fromFile(string $filename): self { if (! is_readable($filename)) { throw new RuntimeException("Failed to read {$filename}."); } $str = file_get_contents($filename); if ($str === false) { throw new RuntimeException("Failed to read {$filename}."); } return self::fromString($str); } /** * Get content type. */ public function type(): string { return $this->type; } public function data(): string { return $this->data; } /** * Encode to PEM string. */ public function string(): string { return "-----BEGIN {$this->type}-----\n" . trim(chunk_split(base64_encode($this->data), 64, "\n")) . "\n" . "-----END {$this->type}-----"; } }