openssl
首先本地需要安裝 openssl,用於生成自簽名證書。
$ brew install openssl
檢查安裝:
$ openssl version
LibreSSL 2.6.5
生成證書
執行以下命令生成證書:
openssl req -nodes -new -x509 -keyout server.key -out server.cert
Generating a 2048 bit RSA private key
執行后會提示輸入一些信息,地址,組織等,可以直接回車跳過。但輸入時 Common Name
時,需要確保輸入 localhost
。
$ openssl req -nodes -new -x509 -keyout server.key -out server.cert
Generating a 2048 bit RSA private key
............+++
..........+++
writing new private key to 'server.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) []:
State or Province Name (full name) []:
Locality Name (eg, city) []:
Organization Name (eg, company) []:
Organizational Unit Name (eg, section) []:
Common Name (eg, fully qualified host name) []:localhost
執行后會得到兩個文件:
server.cert
自簽名證書文件server.key
證書私鑰
服務端代碼
server.js
const http = require("http");
const https = require("https");
const fs = require("fs");
const Koa = require("koa");
const app = new Koa();
app.use(async ctx => {
ctx.body = "hello https";
});
http.createServer(app.callback()).listen(3000);
const options = {
key: fs.readFileSync("./server.key", "utf8"),
cert: fs.readFileSync("./server.cert", "utf8")
};
https.createServer(options, app.callback()).listen(443);
然后訪問 localhost。
本地訪問 https 的效果
因為是本地自簽名證書的原因,並沒有三方機構的認證,所以瀏覽器會有紅色的警告。