master
ブランチ master
LittleBeast / src / Std / Test / Helper / TestCert.php
4.1 KB、99行 生 Blame 履歴
1<?php
2/*************************************************************
3# 076 License
4
5Copyright (c) テクニカル諏訪子
6
7Permission is hereby granted to any person obtaining a copy of the software
8Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
9sublicense, and/or sell copies of the Software, subject to the following conditions:
10
11 1. **Origin Attribution**:
12 - You must not misrepresent the origin of the Software; you must not claim
13 you created the original Software.
14 - If the Software is used in a product, you must either:
15 a. Provide clear attribution in the product's documentation, user interface,
16 or other visible areas, **OR**
17 b. Pay the original developers a fee they specify in writing.
18 2. **Usage Restriction**:
19 - The Software, or any derivative works, dependencies, or libraries
20 incorporating it, must not be used for censorship or to suppress freedom of
21 speech, expression, or creativity. Prohibited uses include, but are not
22 limited to:
23 - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
24 ideas, or objective reality.
25 - Tools or systems designed to restrict access to information or
26 artistic works.
27 3. **Notice Preservation**:
28 - This license and the above copyright notice must remain intact in all copies
29 of the source code.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
32INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
33PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
34HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
35CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
36OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 */
38namespace Std\Test\Helper;
39
40use Std\Lib\Crypto\Ec;
41use Std\Lib\Crypto\Rsa;
42use Std\Lib\Crypto\X509;
43
44/**
45 * テスト用の証明書(CAとそのCAが発行したサーバーの証明書、PHP純正のStd\Lib\Crypto)
46 *
47 * 1つのプロセスで1回だけ作り、一時ファイルに保存する(プロセスの終わりに消す)。
48 *
49 * 例:
50 * $c = TestCert::get();
51 * $srv = MockServer::start('tls-server.php', [$c['cert'], $c['key']]);
52 * $s = Tls::connect('127.0.0.1', $srv->port, ['peer_name' => 'localhost', 'cafile' => $c['ca']]);
53 */
54class TestCert {
55 private static array $cache = [];
56
57 /**
58 * 証明書のファイル
59 *
60 * @param string $type サーバーの鍵:ec(P-256)、rsa(2048ビット)、self(自己署名のP-256)
61 * @return array ca(CAの証明書)、cert(サーバーの証明書)、key(サーバーの秘密鍵)、pub(サーバーの公開鍵)のパス
62 */
63 public static function get(string $type = 'ec'): array {
64 if (isset(self::$cache[$type])) return self::$cache[$type];
65
66 self::$cache['ca'] ??= (function(): array {
67 $key = Rsa::generate(2048);
68 $cert = X509::issue($key, 'LB Test CA', ['ca' => true, 'days' => 30]);
69 return [$key, $cert, self::write('ca.pem', $cert->pem())];
70 })();
71 [$caKey, $caCert, $caFile] = self::$cache['ca'];
72
73 $key = $type === 'rsa' ? Rsa::generate(2048) : Ec::generate('P-256');
74 $opt = ['sans' => ['localhost', '127.0.0.1', '::1'], 'days' => 30];
75 if ($type !== 'self') $opt['issuer'] = [$caCert, $caKey];
76 $cert = X509::issue($key, 'localhost', $opt);
77
78 return self::$cache[$type] = [
79 'ca' => $caFile,
80 'cert' => self::write("{$type}-cert.pem", $cert->pem()),
81 'key' => self::write("{$type}-key.pem", $key->toPem()),
82 'pub' => self::write("{$type}-pub.pem", $key->publicPem()),
83 ];
84 }
85
86 private static function write(string $name, string $data): string {
87 static $dir = null;
88 if ($dir === null) {
89 $dir = sys_get_temp_dir().'/lbcert_'.bin2hex(random_bytes(6));
90 mkdir($dir, 0700);
91 register_shutdown_function(function() use (&$dir): void {
92 foreach (glob($dir.'/*') ?: [] as $f) @unlink($f);
93 @rmdir($dir);
94 });
95 }
96 file_put_contents("{$dir}/{$name}", $data);
97 return "{$dir}/{$name}";
98 }
99}