Flask-MQTT连接HiveMQ云TLS报NO_CIPHERS_AVAILABLE错误及证书疑问
问题描述
我正尝试让Flask应用与HiveMQ Broker集群通信,该集群仅支持通过8883端口的TLS通信。据我了解,这需要一些证书文件,但我找到的相关创建指南都未能解决问题。
以下是无法通过TLS发布消息到主题的测试代码片段:
from flask import Flask, render_template, redirect from flask_mqtt import Mqtt app = Flask(__name__) # MQTT configuration app.config['MQTT_BROKER_URL'] = 'xxxxxxxxxxxxxxxxxxxxx.s2.eu.hivemq.cloud' app.config['MQTT_BROKER_PORT'] = 8883 app.config['MQTT_USERNAME'] = 'my_user_name' app.config['MQTT_PASSWORD'] = 'my_password' app.config['MQTT_TLS_ENABLED'] = True app.config['MQTT_TLS_INSECURE'] = True app.config['MQTT_TLS_CA_CERTS'] = '' # Is this needed? If yes, how is such a file created? app.config['MQTT_TLS_CERTFILE '] = '' # Is this needed? If yes, how is such a file created? app.config['MQTT_TLS_KEYFILE'] = '' # Is this needed? If yes, how is such a file created? mqtt = Mqtt(app) @app.route('/') def index(): return render_template('index.html') @app.route('/publish', methods=['POST']) def publish(): mqtt.publish("control/", "toggle_valve") return redirect('/', 200) if __name__ == '__main__': app.run(debug=True)
参考Flask-MQTT文档示例进行配置,但运行代码时持续出现错误:SSL: NO_CIPHERS_AVAILABLE] no ciphers available。
请问这些证书文件是直接从HiveMQ获取,还是需要用OpenSSL等工具自行创建?
补充信息:已确认URL、端口及用户名密码可用,因为使用paho-mqtt库在Flask外已成功连接。
解决方案
证书配置说明
MQTT_TLS_CA_CERTS:需要配置。HiveMQ Cloud使用公开可信的CA证书(如Let's Encrypt),无需自行创建,直接使用系统默认的CA证书存储路径即可:- Linux:
/etc/ssl/certs/ca-certificates.crt - macOS:
/usr/local/etc/openssl/cert.pem或/etc/ssl/cert.pem - Windows:可通过浏览器导出HiveMQ Cloud域名的根证书,保存为
.crt文件后填写路径
- Linux:
MQTT_TLS_CERTFILE和MQTT_TLS_KEYFILE:无需配置。HiveMQ Cloud采用单向TLS认证,仅客户端验证服务器证书,服务器仅通过用户名密码验证客户端身份,不需要客户端证书和密钥。
修复错误的配置调整
SSL: NO_CIPHERS_AVAILABLE错误源于Flask-MQTT底层的paho-mqtt客户端未正确加载默认加密套件,结合配置缺失导致。调整后的完整代码如下:
from flask import Flask, render_template, redirect from flask_mqtt import Mqtt app = Flask(__name__) # MQTT configuration app.config['MQTT_BROKER_URL'] = 'xxxxxxxxxxxxxxxxxxxxx.s2.eu.hivemq.cloud' app.config['MQTT_BROKER_PORT'] = 8883 app.config['MQTT_USERNAME'] = 'my_user_name' app.config['MQTT_PASSWORD'] = 'my_password' app.config['MQTT_TLS_ENABLED'] = True # 建议关闭INSECURE,避免跳过服务器证书验证(存在安全风险) app.config['MQTT_TLS_INSECURE'] = False # 配置系统默认CA证书路径,根据自身系统替换 app.config['MQTT_TLS_CA_CERTS'] = '/etc/ssl/certs/ca-certificates.crt' # 无需配置客户端证书和密钥 # app.config['MQTT_TLS_CERTFILE'] = '' # app.config['MQTT_TLS_KEYFILE'] = '' mqtt = Mqtt(app) @app.route('/') def index(): return render_template('index.html') @app.route('/publish', methods=['POST']) def publish(): mqtt.publish("control/", "toggle_valve") return redirect('/', 200) if __name__ == '__main__': app.run(debug=True)
额外注意事项
- 更新依赖包,避免旧版本的加密套件支持问题:
pip install --upgrade paho-mqtt flask-mqtt - 若仍出现 cipher 相关错误,可手动指定HiveMQ Cloud支持的加密套件:
app.config['MQTT_TLS_CIPHERS'] = 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256'
内容的提问来源于stack exchange,提问作者paxel
相关产品推荐
相关产品推荐

