如何產生 0 設定的自簽憑證

產生自簽憑證的方法有很多,最多人使用者方法是使用 OpenSSL 的指令,不過這個方法的指令有點繁瑣可能會產生出不是自己想要的憑證。

mkcert

所以今天就來介紹一個 Tool 它叫做 mkcert 它可以很快速的產生自簽憑證,並且自動讓系統信任它省去很多繁瑣的指令操作

安裝 mkcert

macOS

macOS 的使用者直接使用 brew 安裝即可

brew install mkcert

Linux

Linux 使用者也可以使用 brew 安裝或是直接下載已經 build 好的指令

git clone https://github.com/FiloSottile/mkcert && cd mkcert
go build -ldflags "-X main.Version=$(git describe --tags)"

Windows

Windows 使用者可以使用 choco 安裝

choco install mkcert

或是直接下載 .exe 執行

產生本地可信任的憑證

Tool 安裝後就可以執行以下安裝,假設今天要簽發的憑證是

  • *.example.com
  • example.test
  • localhost
  • 127.0.0.1
  • ::1

就可以直接使用以下指令,執行後就會有憑證檔 ./example.com+5.pem 與金鑰檔 ./example.com+5-key.pem

ubuntu@localhost:~/$ mkcert -install
Created a new local CA 💥
The local CA is now installed in the system trust store! ⚡️
The local CA is now installed in the Firefox trust store (requires browser restart)! 🦊

ubuntu@localhost:~/$ mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1

Created a new certificate valid for the following names 📜
 - "example.com"
 - "*.example.com"
 - "example.test"
 - "localhost"
 - "127.0.0.1"
 - "::1"

The certificate is at "./example.com+5.pem" and the key at "./example.com+5-key.pem" ✅

產生自定義檔名憑證與金鑰

產生的憑證檔名與金鑰檔名想要自行指定可以使用如下,假設今天要產生的網域如

  • example.com
  • *.example.com
ubuntu@localhost:~/cert$ mkcert -key-file key.pem -cert-file cert.pem example.com *.example.com
Created a new local CA 💥
Note: the local CA is not installed in the system trust store.
Run "mkcert -install" for certificates to be trusted automatically ⚠️

Created a new certificate valid for the following names 📜
 - "esun-gvp-mlaas-4core.iot.iptnet.net"

The certificate is at "cert.pem" and the key at "key.pem" ✅

It will expire on 4 October 2024 🗓

產生後預設的 CA 檔案會在 ~/.local/share/mkcert/rootCA/rootCA-key.pem

變更 CA 檔案位置

如果需要改變 CA 的檔案位置可以改變 NODE_EXTRA_CA_CERTS 這個參數,例如想要把 CA 檔案改成 rootCA.pem 可以使用如下的指令然後再次執行 mkcert

export NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem"