1. Create CA Key Pair
Run as administrator the following command:

openssl genrsa -out m2mqtt_ca.key 2048

2. Create CA Certificate
Next I’m creating a certificate for the CA, using the key pair I have created in step 1:

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

3. Create Mosquitto Broker Key Pair
Next, I’m creating a private key for the server (m2mqtt_srv.key) with:

openssl genrsa -out m2mqtt_srv.key 2048

4. Create Certificate Request from CA
That key we need to be certified, so we create a certificate request for it, and the certificate needs to be signed by the CA:

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

5. Verify and Sign the Certificate Request
The last step is to sign the server request through the CA to get the broker certificate:

openssl x509 -req -in m2mqtt_srv.csr -CA m2mqtt_ca.crt -CAkey m2mqtt_ca.key -CAcreateserial -out m2mqtt_srv.crt -days 3650

文件清单

m2mqtt_ca.crt : CA Certificate
m2mqtt_ca.key : CA key pair (private, public)
m2mqtt_ca.srl : CA serial number file
m2mqtt_srv.crt : server certificate
m2mqtt_srv.csr : certificate sign request, not needed any more
m2mqtt_srv.key : server key pair

将证书和密钥文件复制到下面目录
/etc/mosquitto/certs
最后目录内容应该类似这样
/etc/mosquitto/certs/m2mqtt_ca.crt
/etc/mosquitto/certs/m2mqtt_srv.crt
/etc/mosquitto/certs/m2mqtt_srv.key

修改/etc/mosquitto/mosquitto.conf配置文件
默认端口号

port 8883

指定证书文件与路径信息

#capath
cafile /etc/mosquitto/certs/m2mqtt_ca.crt

# Path to the PEM encoded server certificate.
certfile /etc/mosquitto/certs/m2mqtt_srv.crt

# Path to the PEM encoded keyfile.
keyfile /etc/mosquitto/certs/m2mqtt_srv.key

# This option defines the version of the TLS protocol to use for this listener.
# The default value allows v1.2, v1.1 and v1.0, if they are all supported by
# the version of openssl that the broker was compiled against. For openssl >=
# 1.0.1 the valid values are tlsv1.2 tlsv1.1 and tlsv1. For openssl < 1.0.1 the
# valid values are tlsv1.
tls_version tlsv1.2

配置文件最终结果

 cat /etc/mosquitto/conf.d/tls.conf 

port 8883
cafile /etc/mosquitto/certs/m2mqtt_ca.crt
certfile /etc/mosquitto/certs/m2mqtt_srv.crt
keyfile /etc/mosquitto/certs/m2mqtt_srv.key
tls_version tlsv1.2

运行测试

mosquitto -c mosquitto.conf -v

systemd服务查看

sudo systemctl status mosquitto

● mosquitto.service - LSB: mosquitto MQTT v3.1 message broker
Loaded: loaded (/etc/init.d/mosquitto; generated)
Active: active (running) since Wed 2022-10-19 09:53:21 CST; 2min 32s ago

本文链接地址:https://const.net.cn/728.html

标签: none

添加新评论