Photo by Jon Moore on Unsplash

建立本機 RCA(Root Certificate Authority) 來通過瀏覽器 localhost HTTPS「譯 + 實作」

Whien
5 min readOct 5, 2018

在 localhost 開發時如果有 https only 的需求,又想在 localhost 使用正確的 HTTPS 而不是略過使畫面顯示不安全,只要幾個步驟,就可以很快速的發給自己一個 localhost 的 CA(Certificate Authority),也順便可以了解 CA

參考資料:https://deliciousbrains.com/ssl-certificate-authority-for-local-https-development/

建立 Root Certificate Authority

就像一個最大機構的認證證書一樣,而這個證書會通過一把私鑰並產生

產生私鑰

> openssl genrsa -des3 -out myCA.key 2048

輸入私鑰密碼(這組密碼會對應到之後要產生的證書):這裡我輸入 0000

產生證書

openssl req -x509 -new -nodes -key myCA.key -sha256 -days 1825 -out myCA.pem

在此步驟需要輸入一些證書上的相關資訊

將證書放入鑰匙圈中存取

使用 MAC Spotlite 搜尋鑰匙圈存取(keychain Access.app),然後直接把產生出來的 myCA.pem 直接拉進去。

點擊兩下打開,選擇信任並且「永遠信任」

就完成第一步了。

建立 CA-Signed Certificates

步驟很類似

首先產生私鑰

openssl genrsa -out localhost.key 2048

透過私鑰建立 CSR

openssl req -new -key localhost.key -out localhost.csr

相同的,輸入這張證書的訊息,並且最後密碼要與 RCA 一致為:0000

定義 Subject Alternative Name (SAN) extension

這部分是要設定一些證書的相關參數與限定的 domain,建立一個名稱為 localhost.ext 的檔案,並且內容為

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost

產生 certificate

> openssl x509 -req -in localhost.csr -CA myCA.pem -CAkey myCA.key -CAcreateserial -out localhost.crt -extfile localhost.ext

輸入密碼為 0000

成功後就會有「localhost.crt」及「localhost.key」檔案

建立 Web HTTPS Server

用 node 很快的來驗證一下 https 是否成功

創建一個 ssl 資料夾

將檔案移動至 ssl

創建一個 server.js 檔案

內容為

const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('ssl/localhost.key'),
cert: fs.readFileSync('ssl/localhost.crt')
};
https
.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
})
.listen(8000);

啟動伺服器

> node server.js

結果

這樣就簡單的的完成了 localhost 的 https 建立囉~~~

我是懷恩(Whien)如果想與我交流,歡迎到 Facebook 加我好友,並且告知一下您是從哪裡看到我的就好囉!Facebook: https://www.facebook.com/haowei.liou

--

--

Whien
Whien

Written by Whien

遨遊在硬體與軟體世界中,對於計算機一切事物都充滿好奇及熱情。

No responses yet