port, ['peer_name' => 'localhost', 'cafile' => $c['ca']]); */ class TestCert { private static array $cache = []; /** * 証明書のファイル * * @param string $type サーバーの鍵:ec(P-256)、rsa(2048ビット)、self(自己署名のP-256) * @return array ca(CAの証明書)、cert(サーバーの証明書)、key(サーバーの秘密鍵)、pub(サーバーの公開鍵)のパス */ public static function get(string $type = 'ec'): array { if (isset(self::$cache[$type])) return self::$cache[$type]; self::$cache['ca'] ??= (function(): array { $key = Rsa::generate(2048); $cert = X509::issue($key, 'LB Test CA', ['ca' => true, 'days' => 30]); return [$key, $cert, self::write('ca.pem', $cert->pem())]; })(); [$caKey, $caCert, $caFile] = self::$cache['ca']; $key = $type === 'rsa' ? Rsa::generate(2048) : Ec::generate('P-256'); $opt = ['sans' => ['localhost', '127.0.0.1', '::1'], 'days' => 30]; if ($type !== 'self') $opt['issuer'] = [$caCert, $caKey]; $cert = X509::issue($key, 'localhost', $opt); return self::$cache[$type] = [ 'ca' => $caFile, 'cert' => self::write("{$type}-cert.pem", $cert->pem()), 'key' => self::write("{$type}-key.pem", $key->toPem()), 'pub' => self::write("{$type}-pub.pem", $key->publicPem()), ]; } private static function write(string $name, string $data): string { static $dir = null; if ($dir === null) { $dir = sys_get_temp_dir().'/lbcert_'.bin2hex(random_bytes(6)); mkdir($dir, 0700); register_shutdown_function(function() use (&$dir): void { foreach (glob($dir.'/*') ?: [] as $f) @unlink($f); @rmdir($dir); }); } file_put_contents("{$dir}/{$name}", $data); return "{$dir}/{$name}"; } }