六、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 和 ...
随机推荐
- 以下web.xml片断( )正确地声明servlet 上下文参数。
A <init-param> <param-name>MAX</param-name> <param-value>100</param-value ...
- python XlsxWriter Example: Hello World
http://xlsxwriter.readthedocs.io/example_hello_world.html The simplest possible spreadsheet. This is ...
- [转]Loadrunner经典面试题
http://www.mianwww.com/html/category/it-interview/loadrunner/ 史上最全 在LoadRunner中为什么要设置思考时间和pacing 答: ...
- 网易AI工程师面试常见知识
- A mail sent to Google chromium.org Groups for Help
Hi, I've ported Chromium M39 to 4.4 using WebView. The main modifications are: I changed AwContents: ...
- SQL:CASE WHEN ELSE END用法
CASE WHEN 条件1 THEN 结果1 WHEN 条件2 THEN 结果2 WHEN 条件3 THEN 结果3 WHEN 条件4 THEN 结果4......... ...
- 【BZOJ4864】[BeiJing 2017 Wc]神秘物质 Splay
[BZOJ4864][BeiJing 2017 Wc]神秘物质 Description 21ZZ 年,冬. 小诚退休以后, 不知为何重新燃起了对物理学的兴趣. 他从研究所借了些实验仪器,整天研究各种微 ...
- LeetCode-Combination Sum IV
Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...
- 170320、使用快照和AOF将Redis数据持久化到硬盘中
前言 我们知道Redis是一款内存服务器,就算我们对自己的服务器足够的信任,不会出现任何软件或者硬件的故障,但也会有可能出现突然断电等情况,造成Redis服务器中的数据失效.因此,我们需要向传统的关系 ...
- CH5E01 乌龟棋【线性DP】
5E01 乌龟棋 0x5E「动态规划」练习 描述 小明过生日的时候,爸爸送给他一副乌龟棋当作礼物.乌龟棋的棋盘是一行N 个格子,每个格子上一个分数(非负整数).棋盘第1 格是唯一的起点,第N 格是终点 ...