第7章 Mosquitto增加SSL/TLS加密通信
本章详细介绍了MQTT通信中的TLS加密配置。主要内容包括:TLS基础知识与加密原理;X.509证书类型及自签名证书生成流程;Mosquitto服务器的单向/双向认证配置方法;客户端连接的安全参数设置;TLS握手过程详解;以及安全检查清单,涵盖证书有效性、加密套件选择、协议版本控制等关键安全要素。通过本章学习,读者能够为Mosquitto搭建安全的TLS加密通信环境,确保MQTT数据传输的机密性、
·
第7章 SSL/TLS加密通信
7.1 TLS基础
7.2 证书类型
7.3 生成自签名证书
#!/bin/bash
# 生成CA私钥
openssl genrsa -out ca.key 2048
# 生成CA证书
openssl req -new -x509 -days 3650 -key ca.key -out ca.crt \
-subj "/CN=MQTT CA"
# 生成服务器私钥
openssl genrsa -out server.key 2048
# 生成服务器CSR
openssl req -new -key server.key -out server.csr \
-subj "/CN=mosquitto-server"
# CA签名服务器证书
openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey ca.key \
-CAcreateserial -out server.crt
# 生成客户端私钥
openssl genrsa -out client.key 2048
# 生成客户端CSR
openssl req -new -key client.key -out client.csr \
-subj "/CN=mqtt-client"
# CA签名客户端证书
openssl x509 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key \
-CAcreateserial -out client.crt
echo "证书生成完成!"
证书生成流程
7.4 Mosquitto TLS配置
单向认证(服务器)
# /etc/mosquitto/mosquitto.conf
# TLS监听器
listener 8883
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key
cafile /etc/mosquitto/certs/ca.crt
# 要求TLS
allow_anonymous false
password_file /etc/mosquitto/passwd
双向认证(客户端证书)
listener 8883
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key
cafile /etc/mosquitto/certs/ca.crt
# 要求客户端证书
require_certificate true
use_identity_as_username true
# 或者使用CA验证
tls_version tlsv1.2
7.5 客户端连接
mosquitto_pub/sub
# 单向认证
mosquitto_sub -h broker.example.com -p 8883 \
--cafile /path/to/ca.crt \
-t "test/#"
# 双向认证
mosquitto_pub -h broker.example.com -p 8883 \
--cafile /path/to/ca.crt \
--cert /path/to/client.crt \
--key /path/to/client.key \
-t "test" -m "hello"
# 跳过证书验证(仅测试)
mosquitto_sub -h localhost -p 8883 \
--insecure \
-t "test/#"
Python客户端
import paho.mqtt.client as mqtt
client = mqtt.Client()
client.tls_set(
ca_certs="/path/to/ca.crt",
certfile="/path/to/client.crt",
keyfile="/path/to/client.key",
tls_version=ssl.PROTOCOL_TLSv1_2
)
client.connect("broker.example.com", 8883)
7.6 TLS握手流程
7.7 安全检查清单
7.8 本章小结
掌握了Mosquitto的TLS配置,实现了安全的MQTT通信。
更多推荐
所有评论(0)