MQTT broker搭建并用SSL加密

2024-09-07 10:20

本文主要是介绍MQTT broker搭建并用SSL加密,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

系统为centos,基于emqx搭建broker,流程参考官方。

安装好后,用ssl加密。

进入/etc/emqx/certs,可以看到
在这里插入图片描述
分别为

  • cacert.pem CA 文件
  • cert.pem 服务端证书
  • key.pem 服务端key
  • client-cert.pem 客户端证书
  • client-key.pem 客户端key
    编辑emqx配置:vim /etc/emqx/emqx.conf,添加ssl配置:
listeners.ssl.default {# 端口bind = "0.0.0.0:8883"ssl_options {cacertfile = "/etc/emqx/certs/cacert.pem" #CA文件certfile = "/etc/emqx/certs/cert.pem"    #服务端证书keyfile = "/etc/emqx/certs/key.pem"   #服务端keyverify = verify_peer  # 双向认证fail_if_no_peer_cert = true}
}

再在客户端(如MQTTX)配置连接信息:在这里插入图片描述

Springboot订阅MQTTS

添加依赖

        <!--mqtt--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-integration</artifactId></dependency><dependency><groupId>org.springframework.integration</groupId><artifactId>spring-integration-stream</artifactId></dependency><dependency><groupId>org.springframework.integration</groupId><artifactId>spring-integration-mqtt</artifactId></dependency><!--ssl--><dependency><groupId>org.bouncycastle</groupId><artifactId>bcpkix-jdk15on</artifactId><version>1.64</version></dependency>

配置

spring:mqtt:provider:#MQTTS服务地址,端口号默认8883,如果有多个,用逗号隔开url: ssl://192.168.1.xx:8883#用户名username: xx#密码password: xxxx#客户端id(不能重复)client:id: provider-id#MQTT默认的消息推送主题,实际可在调用接口是指定default:topic: topicconsumer:url: ssl://192.168.1.xx:8883#用户名username: xx#密码password: xxxx#客户端id(不能重复)client:id: consumer-id#MQTT默认的消息推送主题,实际可在调用接口时指定default:topic: topic

Mqtt配置

@Configuration
public class MqttConsumerConfig {@Value("${spring.mqtt.consumer.username}")private String username;@Value("${spring.mqtt.consumer.password}")private String password;@Value("${spring.mqtt.consumer.url}")private String hostUrl;@Value("${spring.mqtt.consumer.client.id}")private String clientId;@Value("${spring.mqtt.consumer.default.topic}")private String defaultTopic;// 把证书文件放在在resource的ssl_certs目录下String caFilePath = "/ssl_certs/cacert.pem";String clientCrtFilePath = "/ssl_certs/client-cert.pem";String clientKeyFilePath = "/ssl_certs/client-key.pem";/*** 客户端对象*/private MqttClient client;/*** 在bean初始化后连接到服务器*/@PostConstructpublic void init() {connect();}/*** 客户端连接服务端*/@SneakyThrowspublic void connect() {
//        try {//创建MQTT客户端对象client = new MqttClient(hostUrl, clientId, new MemoryPersistence());//连接设置MqttConnectOptions options = new MqttConnectOptions();SSLSocketFactory socketFactory = getSocketFactory(caFilePath,clientCrtFilePath, clientKeyFilePath, "");options.setSocketFactory(socketFactory);/*允许所有host连接*/options.setSSLHostnameVerifier((s, sslSession) -> true);/*不配置可能出现报错java.security.cert.CertificateException: No subject alternative names present*/options.setHttpsHostnameVerificationEnabled(false);//是否清空session,设置为false表示服务器会保留客户端的连接记录,客户端重连之后能获取到服务器在客户端断开连接期间推送的消息//设置为true表示每次连接到服务端都是以新的身份options.setCleanSession(true);//设置连接用户名options.setUserName(username);//设置连接密码options.setPassword(password.toCharArray());//设置超时时间,单位为秒options.setConnectionTimeout(100);//设置心跳时间 单位为秒,表示服务器每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线options.setKeepAliveInterval(20);//设置遗嘱消息的话题,若客户端和服务器之间的连接意外断开,服务器将发布客户端的遗嘱信息options.setWill("willTopic", (clientId + "与服务器断开连接").getBytes(), 0, false);options.setAutomaticReconnect(true);//设置回调client.setCallback(new MqttCallbackImpl());client.connect(options);System.out.println(" 客户端连接成功 ");//订阅主题//消息等级,和主题数组一一对应,服务端将按照指定等级给订阅了主题的客户端推送消息int[] qos = {1, 1};//主题String[] topics = {"topicX#", "topicY#"};//订阅主题
//            client.subscribe("topicX",1);client.subscribe(topics);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }}/*** 断开连接*/public void disConnect() {try {client.disconnect();} catch (MqttException e) {e.printStackTrace();}}/*** 订阅主题*/public void subscribe(String topic, int qos) {try {client.subscribe(topic, qos);} catch (MqttException e) {e.printStackTrace();}}private static SSLSocketFactory getSocketFactory(final String caCrtFile,final String crtFile, final String keyFile, final String password)throws Exception {ClassPathResource caCrtFileRes = new ClassPathResource(caCrtFile);ClassPathResource crtFileRes = new ClassPathResource(crtFile);ClassPathResource keyFileRes = new ClassPathResource(keyFile);// add BouncyCastle providerSecurity.addProvider(new BouncyCastleProvider());// load CA certificateX509Certificate caCert = null;BufferedInputStream bis = new BufferedInputStream(caCrtFileRes.getStream());CertificateFactory cf = CertificateFactory.getInstance("X.509");while (bis.available() > 0) {caCert = (X509Certificate) cf.generateCertificate(bis);// System.out.println(caCert.toString());}// load client certificatebis = new BufferedInputStream(crtFileRes.getStream());X509Certificate cert = null;while (bis.available() > 0) {cert = (X509Certificate) cf.generateCertificate(bis);// System.out.println(caCert.toString());}// load client private keyPEMParser pemParser = new PEMParser(new InputStreamReader(keyFileRes.getStream()));Object object = pemParser.readObject();PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");KeyPair key;if (object instanceof PEMEncryptedKeyPair) {System.out.println("Encrypted key - we will use provided password");key = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));} else {System.out.println("Unencrypted key - no password needed");key = converter.getKeyPair((PEMKeyPair) object);}pemParser.close();// CA certificate is used to authenticate serverKeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());caKs.load(null, null);caKs.setCertificateEntry("ca-certificate", caCert);TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");tmf.init(caKs);// client key and certificates are sent to server so it can authenticate// usKeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());ks.load(null, null);ks.setCertificateEntry("certificate", cert);ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(),new java.security.cert.Certificate[]{cert});KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());kmf.init(ks, password.toCharArray());// finally, create SSL socket factorySSLContext context = SSLContext.getInstance("TLSv1.2");context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);return context.getSocketFactory();}}
@Slf4j
@Component
public class MqttCallbackImpl implements MqttCallback {@Overridepublic void connectionLost(Throwable throwable) {log.info("[MQTT] 连接断开");}@Overridepublic void messageArrived(String topic, MqttMessage message) throws Exception {String msg = new String(message.getPayload());log.info(String.format("接收消息主题 : %s", topic));log.info(String.format("接收消息Qos : %d", message.getQos()));log.info(String.format("接收消息内容 : %s", msg));log.info(String.format("接收消息retained : %b", message.isRetained()));}@Overridepublic void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {log.info("发送消息成功");}
}

这篇关于MQTT broker搭建并用SSL加密的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1144797

相关文章

SpringBoot3使用Jasypt实现加密配置文件

《SpringBoot3使用Jasypt实现加密配置文件》这篇文章主要为大家详细介绍了SpringBoot3如何使用Jasypt实现加密配置文件功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编... 目录一. 使用步骤1. 添加依赖2.配置加密密码3. 加密敏感信息4. 将加密信息存储到配置文件中5

SpringBoot整合jasypt实现重要数据加密

《SpringBoot整合jasypt实现重要数据加密》Jasypt是一个专注于简化Java加密操作的开源工具,:本文主要介绍详细介绍了如何使用jasypt实现重要数据加密,感兴趣的小伙伴可... 目录jasypt简介 jasypt的优点SpringBoot使用jasypt创建mapper接口配置文件加密

Java实现MD5加密的四种方式

《Java实现MD5加密的四种方式》MD5是一种广泛使用的哈希算法,其输出结果是一个128位的二进制数,通常以32位十六进制数的形式表示,MD5的底层实现涉及多个复杂的步骤和算法,本文给大家介绍了Ja... 目录MD5介绍Java 中实现 MD5 加密方式方法一:使用 MessageDigest方法二:使用

Python如何获取域名的SSL证书信息和到期时间

《Python如何获取域名的SSL证书信息和到期时间》在当今互联网时代,SSL证书的重要性不言而喻,它不仅为用户提供了安全的连接,还能提高网站的搜索引擎排名,那我们怎么才能通过Python获取域名的S... 目录了解SSL证书的基本概念使用python库来抓取SSL证书信息安装必要的库编写获取SSL证书信息

使用DeepSeek搭建个人知识库(在笔记本电脑上)

《使用DeepSeek搭建个人知识库(在笔记本电脑上)》本文介绍了如何在笔记本电脑上使用DeepSeek和开源工具搭建个人知识库,通过安装DeepSeek和RAGFlow,并使用CherryStudi... 目录部署环境软件清单安装DeepSeek安装Cherry Studio安装RAGFlow设置知识库总

Linux搭建Mysql主从同步的教程

《Linux搭建Mysql主从同步的教程》:本文主要介绍Linux搭建Mysql主从同步的教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux搭建mysql主从同步1.启动mysql服务2.修改Mysql主库配置文件/etc/my.cnf3.重启主库my

国内环境搭建私有知识问答库踩坑记录(ollama+deepseek+ragflow)

《国内环境搭建私有知识问答库踩坑记录(ollama+deepseek+ragflow)》本文给大家利用deepseek模型搭建私有知识问答库的详细步骤和遇到的问题及解决办法,感兴趣的朋友一起看看吧... 目录1. 第1步大家在安装完ollama后,需要到系统环境变量中添加两个变量2. 第3步 “在cmd中

nginx生成自签名SSL证书配置HTTPS的实现

《nginx生成自签名SSL证书配置HTTPS的实现》本文主要介绍在Nginx中生成自签名SSL证书并配置HTTPS,包括安装Nginx、创建证书、配置证书以及测试访问,具有一定的参考价值,感兴趣的可... 目录一、安装nginx二、创建证书三、配置证书并验证四、测试一、安装nginxnginx必须有"-

SpringBoot使用Jasypt对YML文件配置内容加密的方法(数据库密码加密)

《SpringBoot使用Jasypt对YML文件配置内容加密的方法(数据库密码加密)》本文介绍了如何在SpringBoot项目中使用Jasypt对application.yml文件中的敏感信息(如数... 目录SpringBoot使用Jasypt对YML文件配置内容进行加密(例:数据库密码加密)前言一、J

Qt 中集成mqtt协议的使用方法

《Qt中集成mqtt协议的使用方法》文章介绍了如何在工程中引入qmqtt库,并通过声明一个单例类来暴露订阅到的主题数据,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一,引入qmqtt 库二,使用一,引入qmqtt 库我是将整个头文件/源文件都添加到了工程中进行编译,这样 跨平台