原文發佈於:mengqi.info/html/2019/2…html
在作程序開發的時候,免不了要接觸https加密通訊,你可能須要本身生成證書,雖然可使用openssl完成這個工做,可是openssl是一個龐大和複雜的工具,有着使人眼花繚亂的參數,若是你沒有太多的密碼學知識,只是爲了在本機生成一個自簽名證書,方便本身開發和測試,那麼能夠試一試這個用Go語言寫的命令行工具:mkcert,很是簡單易用。linux
mkcert的Github地址:github.com/FiloSottile…,該項目有18000多顆星,做者Filippo Valsorda在2018年加入了Go的開發團隊。關於mkcert,做者給出的一句話介紹:git
mkcert is a simple tool for making locally-trusted development certificates. It requires no configuration.github
做者提供了編譯好的二進制程序,包含Linux/Windows/macOS三個版本,可直接下載使用:github.com/FiloSottile…。你也可使用brew安裝,或者經過源碼編譯,具體詳見做者在Github上面的說明。web
下面,我以debian linux爲例,介紹一下mkcert 1.3的使用方式:chrome
ln -s ~/download/mkcert-v1.3.0-linux-amd64 ~/bin/mkcert
chmod u+x ~/bin/mkcert
複製代碼
sudo apt install libnss3-tools
複製代碼
~/.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服務(使用較低的端口須要使用管理員權限),具體命令以下:bash
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>
複製代碼