在服務器電腦上面創建myCA文件夾, 如在/home/qa/ 文件夾下使用命令,
mkdir myCA
然后執行以下命令,我們將創建並使用其他用戶沒有權限訪問的目錄。
sudo chmod 700
cd myCA
進入myCA文件夾,然后執行以下命令下載生成證書用的腳本。
wget https://github.com/owntracks/tools/raw/master/TLS/generate-CA.sh
下載完之后,在myCA文件夾下面執行命令
注:在生產環境中使用此實例之前,你應該定制the generate-CA.sh腳本
bash ./generate-CA.sh
generate-CA.sh會產生3個文件:ca.crt,ca.key,ca.csr分別為: 證書(.CRT),鑰匙(.KEY),請求(.csr文件),這三個文件是給服務器使用的
在myCA文件夾下面執行命令
bash ./generate-CA.sh client myclient
其中myclient是給客戶端生成證書的名稱,可隨意更改。執行完上述命令后,會新生成幾個文件。
客戶端需要使用的是ca.crt/myclient.crt/myclient.key這三個文件。
經過上述步驟之后,生成了服務器使用的ca.crt/localhost.crt/localhost.key文件和客戶端使用的
ca.crt/myclient.crt/myclient.key這幾個文件,其中ca.crt是同一個文件。
配置mosquitto.conf文件。該文件在mosquitto-1.4.11安裝文件夾里面,打開該文件,修改成如下配置:
port 8883 protocol mqtt cafile /home/myCA/ubuntu/ca.crt certfile /home/myCA/ubuntu/localhost.crt keyfile /home/myCA/ubuntu/localhost.key require_certificate true use_identity_as_username true
修改完配置文件之后,執行啟動命令mosquitto -c /home/qa/mosquitto-1.4.11/mosquitto.conf -v
根據自己的mosquitto-conf文件所在的位置修改上述命令中的參數,然后服務器就以SSL/TSL的方式開始啟動。
此時客戶端使用上述過程產生的客戶端證書連接該服務器,即可進行通信。
參考頁面:https://mosquitto.org/man/mosquitto-tls-7.html