使用mkcert建立自簽名證書
原文釋出於: mengqi.info/html/2019/2…
在做程式開發的時候,免不了要接觸https加密通訊,你可能需要自己生成證書,雖然可以使用openssl完成這個工作,但是openssl是一個龐大和複雜的工具,有著令人眼花繚亂的引數,如果你沒有太多的密碼學知識,只是為了在本機生成一個自簽名證書,方便自己開發和測試,那麼可以試一試這個用Go語言寫的命令列工具:mkcert,非常簡單易用。
mkcert的Github地址: github.com/FiloSottile… ,該專案有18000多顆星,作者Filippo Valsorda在2018年加入了Go的開發團隊。關於mkcert,作者給出的一句話介紹:
mkcert is a simple tool for making locally-trusted development certificates. It requires no configuration.
作者提供了編譯好的二進位制程式,包含Linux/Windows/macOS三個版本,可直接下載使用: github.com/FiloSottile… 。你也可以使用brew安裝,或者通過原始碼編譯,具體詳見作者在Github上面的說明。
下面,我以debian linux為例,介紹一下mkcert 1.3的使用方式:
- 將mkcert下載以後,放到一個合適的地方,並新增執行許可權:
ln -s ~/download/mkcert-v1.3.0-linux-amd64 ~/bin/mkcert chmod u+x ~/bin/mkcert 複製程式碼
- 在linux下,mkcert依賴certutil,如果沒有安裝certutil,可以使用下面的命令安裝:
sudo apt install libnss3-tools 複製程式碼
- 生成CA(certificate authority,即證書頒發機構),執行下面的命令可以在
~/.local/share/mkcert/
生成rootCA.pem
和rootCA-key.pem
兩個檔案,這個命令只需執行一次,因為生成的CA可以反覆使用;
mkcert -install 複製程式碼
- 建立自簽名證書,例如要為域名:
test.local
和IP:127.0.0.1
建立證書,可以使用如下的命令:
mkcert test.local 127.0.0.1 複製程式碼
上述命令會自動使用第3步建立的CA生成證書檔案,其中 xxx.pem
為證書, xxx-key.pem
為私鑰,你也可以使用 -cert-file
和 -key-file
兩個引數設定生成檔案的檔名。
生成了證書和私鑰以後,就可以在web伺服器開啟https了。
以我自己的web伺服器 ran 為例,可以使用 -cert
和 -key
引數設定證書和私鑰的路徑,這時會預設在443埠開啟web服務(使用較低的埠需要使用管理員許可權),具體命令如下:
sudo ran -l -cert /path/to/cert -key /path/to/key 複製程式碼
接下來,可以開啟瀏覽器測試一下了:

從上圖可以看到,chrome瀏覽器位址列中顯示了一把小鎖,表示是安全的連線。如果把地址修改成 https://127.0.0.2
,瀏覽器就會提示為不安全的連線,這是因為剛才使用mkcert建立證書的時侯,並沒有設定 127.0.0.2
這個地址。

在使用mkcert的過程中,我發現了一個問題:雖然生成的證書在瀏覽器裡會顯示為安全的,但是使用curl測試的時候卻報錯了,意思大概就是找不到自建的CA:
$ curl https://127.0.0.1 curl: (60) SSL certificate problem: unable to get local issuer certificate More details here: https://curl.haxx.se/docs/sslcerts.html curl failed to verify the legitimacy of the server and therefore could not establish a secure connection to it. To learn more about this situation and how to fix it, please visit the web page mentioned above. 複製程式碼
我在終端裡找到了剛才執行 mkcert -install
時出現的提示:
Using the local CA at "/home/<user>/.local/share/mkcert" Installing to the system store is not yet supported on this Linux but Firefox and/or Chrome/Chromium will still work. You can also manually install the root certificate at "/home/<user>/.local/share/mkcert/rootCA.pem". The local CA is now installed in the Firefox and/or Chrome/Chromium trust store (requires browser restart)! 複製程式碼
裡面有一句:Installing to the system store is not yet supported on this Linux。
好吧,那麼我來手工安裝一下剛才生成的CA(以下命令均需要用管理員許可權執行):
- 進入
/usr/share/ca-certificates
資料夾,建立一個新資料夾local
,在這個資料夾中建立一個指向mkcert
生成的證書的軟連結:
cd /usr/share/ca-certificates mkdir local cd local ln -s /home/<user>/.local/share/mkcert/rootCA.pem my-local-ca.crt 複製程式碼
- 編輯檔案
/etc/ca-certificates.conf
,新增一行:
local/my-local-ca.crt 複製程式碼
- 執行下面的命令:
update-ca-certificates 複製程式碼
這樣,使用curl連線的時候就沒有報錯了:
$ curl https://127.0.0.1 <h1>hello world</h1> 複製程式碼