mosquitto 开启密码验证,使用TLS加密

技术 · 03-10 · 130 人浏览

本篇文章是对之前的补充。

开启密码验证

编辑配置文件:

vim /etc/mosquitto/mosquitto.conf

将 allow_anonymous 设置为 false,禁止匿名登录。

指定密码存储文件:password_file /etc/mosquitto/pwfile

保存配置,随后创建密码存储文件。

touch /etc/mosquitto/pwfile

接下来添加一个用户。

mosquitto_passwd -b /etc/mosquitto/pwfile 用户名 密码

重启 mosquitto 服务。

systemctl restart mosquitto

使用TLS加密

进入 /etc/mosquitto 目录。

cd /etc/mosquitto

创建一个名为 key 的文件夹,用于存储证书。

mkdir key
cd key

生成 CA 的证书和密钥:

生成 CA 密钥

openssl genrsa -des3 -out ca.key 2048

这里需要设置密码,请牢记,该命令将生成 ca.key 文件。

pF24iid.md.png

生成 CA 证书

openssl req -new -x509 -days 3650 -key ca.key -out ca.crt

输入 ca.key 的密码,填写必要信息。尤其要注意 Common Name 的填写,

pF243zq.md.png

生成 Server 的证书和密钥:

生成 Server 密钥

openssl genrsa -out server.key 2048

这里如果加上 -des3,则后续使用都需要输入密码。

pF24NeU.md.png

生成 Server 请求文件

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

pF24ao4.md.png

生成 Server 证书

openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 3650

pF240Y9.md.png

修改 mosquitto 配置文件,加入:

cafile /etc/mosquitto/key/ca.crt
certfile /etc/mosquitto/key/server.crt
keyfile /etc/mosquitto/key/server.key

随后重启 mosquitto 服务即可。

物联网 技术
Theme Jasmine by Kent Liao