設定macOS本地端HTTPs/SSL證書

1. 確保你有安裝 openssl

2. 創建一個儲存SSL憑證的檔案夾

3. 用RSA算法產生host端的公私鑰(2048 bit)

sudo openssl genrsa -out localhost.key 2048
sudo openssl rsa -in localhost.key -out localhost.key.rsa

4. 創建一個等一下用的設定檔localhost.conf

sudo nano localhost.conf
[req]
default_bits = 1024
distinguished_name = req_distinguished_name
req_extensions = v3_req
[req_distinguished_name][v3_req]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
DNS.2 = *.local
你知道嗎?在系統偏好設定->共享 的最上面是你的電腦在本地網路的暱稱,就算你的電腦IP位置有改變,其他電腦還是可以通過 xxx.local 找到你的電腦喔。

5. 創建證書署名要求(CSR)

sudo openssl req -new -key localhost.key.rsa -subj "/C=TW/ST=Taipei City/L=Daan District/O=HappinessNeverEnds/CN=localhost/" -out localhost.csr -config localhost.conf

6. 創建並簽署你的SSL證書(CRT)

sudo openssl x509 -req -extensions v3_req -days 365 -in localhost.csr -signkey localhost.key.rsa -out localhost.crt -extfile localhost.conf

7. 讓連接的客戶端承認這個證書

Mac 的話請跑:

sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain localhost.crt

Windows 10的話(我自己沒測過):

8. 伺服器設定

npm init
npm install express
mkdir src && cd src
nano index.js
var fs = require('fs');var http = require('http');var https = require('https');var privateKey  = fs.readFileSync('src/localhost.key');var certificate = fs.readFileSync('src/localhost.crt');var credentials = {key: privateKey, cert: certificate};var express = require('express');var app = express();var httpServer = http.createServer(app);var httpsServer = https.createServer(credentials, app);httpServer.listen(8080);httpsServer.listen(8443);
cd ..
node src/index.js

Trouble shooting

localhost.conf
localhost.crt
localhost.csr
localhost.key
localhost.key.rsa

--

--

A broke coder, designer, etc. Fun game.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store