六、Mosquitto 高级应用之SSL/TLS
mosquitto提供SSL支持加密的网络连接和身份验证、本章节讲述次功能的实现、 在此之前需要一些准备工作。
准本工作: 一台 Linux 服务器、 安装好 openssl (不会明白怎么安装 openssl 的可以在网上搜索下、 我就不在这讲解了)
准本工作完成后我们开始来制作所需要的证书。
注:在生成证书过程 在需要输入 【Common Name 】 参数的地方 输入主机ip
一、Certificate Authority
Generate a certificate authority certificate and key.
openssl req -newkey rsa:2045 -x509 -nodes -sha256 -days 36500 -extensions v3_ca -keyout ca.key -out ca.crt
二、Server
Generate a server key.
openssl genrsa -des3 -out server.key 2048
Generate a server key without encryption.
openssl genrsa -out server.key 2048
Generate a certificate signing request to send to the CA.
openssl req -out server.csr -key server.key -new
Send the CSR to the CA, or sign it with your CA key:
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days <duration>
三、Client
Generate a client key.
openssl genrsa -des3 -out client.key 2048
Generate a certificate signing request to send to the CA.
openssl req -out client.csr -key client.key -new
Send the CSR to the CA, or sign it with your CA key:
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days <duration>
到此处证书基本生成完成、 此时会在对应的目录下生成如下证书
ca.crt ca.key ca.srl client.crt client.csr client.key server.crt server.csr server.key
Server 端:ca.crt、 client.crt 、server.key
Client 端:ca.crt、 client.csr client.key
其中 ca.crt 是同一个证书。
四、Mosquitto 服务进行配置证书
1> 打开配置文件 mosquitto.conf 修改如下配置
cafile /home/mosquitto-CA/ssl/ca.crt // 对应上述生成证书的绝对路劲
certfile /home/mosquitto-CA/ssl/server.crt
certfile /home/mosquitto-CA/ssl/server.key
require_certificate true
use_identity_as_username true
配置完成后 保存退出 到这 SSL/TLS 功能基本完成。
2> 启动 Mosquitto 服务
mosquitto -c mosquitto.conf –v
五、Java 端实现
Java 端的 SSL 客户端的实现和<<Mosquitto Java 客户端实现>> 讲解的基本一致 在这就不多做解释了、直接放代码。
需要引入依赖
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.0.</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.45</version>
</dependency>
1> ClientMQTT
import java.util.concurrent.ScheduledExecutorService; import javax.net.ssl.SSLSocketFactory; import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; public class ClientMQTT { public static final String HOST = "ssl://172.16.192.102:1883";
public static final String TOPIC = "root/topic/123";
private static final String clientid = "client11";
private MqttClient client;
private MqttConnectOptions options;
private String userName = "admin";
private String passWord = "admin";
public static String caFilePath = "D:/keystore/Mosquitto-ca/ssl/ca.crt";
public static String clientCrtFilePath = "D:/keystore/Mosquitto-ca/ssl/client.crt";
public static String clientKeyFilePath = "D:/keystore/Mosquitto-ca/ssl/client.key"; private ScheduledExecutorService scheduler; private void start() {
try {
// host为主机名,clientid即连接MQTT的客户端ID,一般以唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
client = new MqttClient(HOST, clientid, new MemoryPersistence());
// MQTT的连接设置
options = new MqttConnectOptions();
// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession(true);
// 设置连接的用户名
options.setUserName(userName);
// 设置连接的密码
options.setPassword(passWord.toCharArray());
// 设置超时时间 单位为秒
options.setConnectionTimeout(10);
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
options.setKeepAliveInterval(20);
// 设置回调
client.setCallback(new PushCallback());
MqttTopic topic = client.getTopic(TOPIC);
// setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
options.setWill(topic, "close".getBytes(), 2, true);
SSLSocketFactory factory = SslUtil.getSocketFactory(caFilePath, clientCrtFilePath, clientKeyFilePath,
"111111");
options.setSocketFactory(factory);
client.connect(options);
// 订阅消息
int[] Qos = { 1 };
String[] topic1 = { TOPIC };
client.subscribe(topic1, Qos); } catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) throws MqttException {
ClientMQTT client = new ClientMQTT();
client.start();
}
}
2> ServerMQTT
/**
*
* Title:Server Description: 服务器向多个客户端推送主题,即不同客户端可向服务器订阅相同主题
*
* @author yueli 2017年9月1日下午17:41:10
*/
public class ServerMQTT { // tcp://MQTT安装的服务器地址:MQTT定义的端口号
public static final String HOST = "ssl://172.16.192.102:1883";
// 定义一个主题
public static final String TOPIC = "root/topic/123";
// 定义MQTT的ID,可以在MQTT服务配置中指定
private static final String clientid = "server11"; private MqttClient client;
private MqttTopic topic11;
private String userName = "mosquitto";
private String passWord = "mosquitto";
public static String caFilePath = "D:/keystore/Mosquitto-ca/ssl/ca.crt";
public static String clientCrtFilePath = "D:/keystore/Mosquitto-ca/ssl/client.crt";
public static String clientKeyFilePath = "D:/keystore/Mosquitto-ca/ssl/client.key"; private MqttMessage message; /**
* 构造函数
*
* @throws Exception
*/
public ServerMQTT() throws Exception {
// MemoryPersistence设置clientid的保存形式,默认为以内存保存
client = new MqttClient(HOST, clientid, new MemoryPersistence());
connect();
} /**
* 用来连接服务器
*
* @throws Exception
*/
private void connect() throws Exception {
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(false);
options.setUserName(userName);
options.setPassword(passWord.toCharArray());
// 设置超时时间
options.setConnectionTimeout(10);
// 设置会话心跳时间
options.setKeepAliveInterval(20);
SSLSocketFactory factory = SslUtil.getSocketFactory(caFilePath, clientCrtFilePath, clientKeyFilePath, "111111");
options.setSocketFactory(factory);
try {
client.setCallback(new PushCallback());
client.connect(options); topic11 = client.getTopic(TOPIC);
} catch (Exception e) {
e.printStackTrace();
}
} /**
*
* @param topic
* @param message
* @throws MqttPersistenceException
* @throws MqttException
*/
public void publish(MqttTopic topic, MqttMessage message) throws MqttPersistenceException, MqttException {
MqttDeliveryToken token = topic.publish(message);
token.waitForCompletion();
System.out.println("message is published completely! " + token.isComplete());
} /**
* 启动入口
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ServerMQTT server = new ServerMQTT(); server.message = new MqttMessage();
server.message.setQos(1);
server.message.setRetained(true);
server.message.setPayload("hello,topic14".getBytes());
server.publish(server.topic11, server.message);
System.out.println(server.message.isRetained() + "------ratained状态");
}
}
3> PushCallback
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage; /**
* 发布消息的回调类
*
* 必须实现MqttCallback的接口并实现对应的相关接口方法CallBack 类将实现 MqttCallBack。
* 每个客户机标识都需要一个回调实例。在此示例中,构造函数传递客户机标识以另存为实例数据。 在回调中,将它用来标识已经启动了该回调的哪个实例。
* 必须在回调类中实现三个方法:
*
* public void messageArrived(MqttTopic topic, MqttMessage message)接收已经预订的发布。
*
* public void connectionLost(Throwable cause)在断开连接时调用。
*
* public void deliveryComplete(MqttDeliveryToken token)) 接收到已经发布的 QoS 1 或 QoS 2
* 消息的传递令牌时调用。 由 MqttClient.connect 激活此回调。
*
*/
public class PushCallback implements MqttCallback { public void connectionLost(Throwable cause) {
// 连接丢失后,一般在这里面进行重连
System.out.println("连接断开,可以做重连");
} public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("deliveryComplete---------" + token.isComplete());
} public void messageArrived(String topic, MqttMessage message) throws Exception {
// subscribe后得到的消息会执行到这里面
System.out.println("接收消息主题 : " + topic);
System.out.println("接收消息Qos : " + message.getQos());
System.out.println("接收消息内容 : " + new String(message.getPayload()));
}
}
4> SslUtil
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.X509Certificate; import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory; import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.*; public class SslUtil {
public static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile,
final String password) throws Exception {
Security.addProvider(new BouncyCastleProvider()); // load CA certificate
PEMReader reader = new PEMReader(
new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
X509Certificate caCert = (X509Certificate) reader.readObject();
reader.close(); // load client certificate
reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
X509Certificate cert = (X509Certificate) reader.readObject();
reader.close(); // load client private key
reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))),
new PasswordFinder() {
@Override
public char[] getPassword() {
return password.toCharArray();
}
});
KeyPair key = (KeyPair) reader.readObject();
reader.close(); // CA certificate is used to authenticate server
KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
caKs.load(null, null);
caKs.setCertificateEntry("ca-certificate", caCert);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(caKs); // client key and certificates are sent to server so it can authenticate
// us
KeyStore 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 factory
SSLContext context = SSLContext.getInstance("TLSv1");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); return context.getSocketFactory();
}
}
到这基本完成 Mosquitto 配置SSL/TLS 功能的实现和测试 。
六、Mosquitto 高级应用之SSL/TLS的更多相关文章
- 基于mosquitto的MQTT服务器---SSL/TLS 单向认证+双向认证
基于mosquitto的MQTT服务器---SSL/TLS 单向认证+双向认证 摘自:https://blog.csdn.net/ty1121466568/article/details/811184 ...
- IE高级配置中,存在SSL支持协议,例如SSL TLS。
IE高级配置中,存在SSL支持协议,例如SSL TLS. 其在注册表的路径为:HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\I ...
- Mosquitto服务器的搭建以及SSL/TLS安全通信配置
Mosquitto服务器的搭建以及SSL/TLS安全通信配置 摘自:https://segmentfault.com/a/1190000005079300 openhab raspberry-pi ...
- mosquitto ---SSL/TLS 单向认证+双向认证
生成证书 # * Redistributions in binary form must reproduce the above copyright # notice, this list of ...
- mosquitto ---配置SSL/TLS linux
mosquitto ---配置SSL/TLS 摘自: https://www.cnblogs.com/saryli/p/9821343.html 在服务器电脑上面创建myCA文件夹, 如在/home/ ...
- mosquitto基于SSL/TLS安全认证测试MQTT
一.环境搭建 1.mosquitto介绍 mosquitto是一个实现了MQTT3.1协议的代理服务器,由MQTT协议创始人之一的Andy Stanford-Clark开发,它为我们提供了非常棒的轻量 ...
- 聊聊HTTPS和SSL/TLS协议
要说清楚 HTTPS 协议的实现原理,至少需要如下几个背景知识.1. 大致了解几个基本术语(HTTPS.SSL.TLS)的含义2. 大致了解 HTTP 和 TCP 的关系(尤其是“短连接”VS“长连接 ...
- 浅谈HTTPS和SSL/TLS协议的背景和基础
相关背景知识要说清楚HTTPS协议的实现原理,至少要需要如下几个背景知识.大致了解几个基础术语(HTTPS.SSL.TLS)的含义大致了解HTTP和TCP的关系(尤其是"短连接"和 ...
- 浅谈 HTTPS 和 SSL/TLS 协议的背景与基础
来自:编程随想 >> 相关背景知识 要说清楚 HTTPS 协议的实现原理,至少需要如下几个背景知识. 大致了解几个基本术语(HTTPS.SSL.TLS)的含义 大致了解 HTTP 和 ...
随机推荐
- openresty package.path require 报错
在文件中 package.path = '/usr/local/share/lua/5.1/?.lua;/usr/local/openresty/lualib/resty/?.lua;' packag ...
- eclipse启动无响应,老是加载不了revert resources,或停留在Loading workbench状态
做开发的同学们或多或少的都会遇到eclipse启动到一定程度时,就进入灰色无响应状态再也不动了.启动画面始终停留在Loading workbench状态.反复重启,状态依旧. 多数情况下,应该是非正常 ...
- PHP 汉字转成拼音
<?php class ZH{ /** * 将字符串转化为拼音 */ function Pinyin($_String, $_Code='gb2312') { $_DataKey =" ...
- C++标准库之mutex
互斥锁有可重入.不可重入之分.C++标准库中用mutex表示不可重入的互斥锁,用recursive_mutex表示可重入的互斥锁.为这两个类增加根据时间来阻塞线程的能力,就又有了两个新的互斥锁:tim ...
- (转自)视频流中的DTS/PTS到底是什么;
翻译了一下: Q:hi,这可能是一个弱智问题,但是当我使用bbMEG1.24beta17编码时,一直以来总是遇到这个下溢的问题.我从日志文件中得到的唯一启示就是我应该更改mux率...但是帮助文档却 ...
- php -- PHP实现点击a标签的href做链接时,直接保存文件(任何类型),而不是通过浏览器直接打开下载的文件
之前做项目遇到这样一个问题,就是在php环境下,用a标签的href链接到一个资源,比如是mp3或者lrc文件时,点击之后不是出现保存文件的提示,而是调用本地程序打开文件或者直接在浏览器上解析.网上说可 ...
- Maven实战(三)——多模块项目的POM重构
在本专栏的上一篇文章POM重构之增还是删中.我们讨论了一些简单有用的POM重构技巧,包含重构的前提--持续集成,以及怎样通过加入或者删除内容来提高POM的可读性和构建的稳定性.但在实际的项目中,这些技 ...
- RAID的简单说明
RAID,为 Redundant Arrays of Independent Disks 的简称,中文为廉价※冗余磁盘阵列 . 磁盘阵列 其实也分为软阵列 (Software Raid) 和硬阵列 ( ...
- 漫游Kafka设计篇之消息传输的事务定义(5)
之前讨论了consumer和producer是怎么工作的,现在来讨论一下数据传输方面.数据传输的事务定义通常有以下三种级别: 最多一次: 消息不会被重复发送,最多被传输一次,但也有可能一次不传输. 最 ...
- 编程之美 set 11 买书问题
题目 书店搞促销, 同时购买多卷书时, 有机会享受优惠 2本优惠 5%, 3本 10%, 4 本 20% 5 本 25% 设计算法, 求解购买一本书的最低价格 分析 1. 第一个感觉是一次购买的越多省 ...