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的更多相关文章

  1. 基于mosquitto的MQTT服务器---SSL/TLS 单向认证+双向认证

    基于mosquitto的MQTT服务器---SSL/TLS 单向认证+双向认证 摘自:https://blog.csdn.net/ty1121466568/article/details/811184 ...

  2. IE高级配置中,存在SSL支持协议,例如SSL TLS。

    IE高级配置中,存在SSL支持协议,例如SSL TLS. 其在注册表的路径为:HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\I ...

  3. Mosquitto服务器的搭建以及SSL/TLS安全通信配置

    Mosquitto服务器的搭建以及SSL/TLS安全通信配置 摘自:https://segmentfault.com/a/1190000005079300 openhab  raspberry-pi ...

  4. mosquitto ---SSL/TLS 单向认证+双向认证

    生成证书 # * Redistributions in binary form must reproduce the above copyright #   notice, this list of ...

  5. mosquitto ---配置SSL/TLS linux

    mosquitto ---配置SSL/TLS 摘自: https://www.cnblogs.com/saryli/p/9821343.html 在服务器电脑上面创建myCA文件夹, 如在/home/ ...

  6. mosquitto基于SSL/TLS安全认证测试MQTT

    一.环境搭建 1.mosquitto介绍 mosquitto是一个实现了MQTT3.1协议的代理服务器,由MQTT协议创始人之一的Andy Stanford-Clark开发,它为我们提供了非常棒的轻量 ...

  7. 聊聊HTTPS和SSL/TLS协议

    要说清楚 HTTPS 协议的实现原理,至少需要如下几个背景知识.1. 大致了解几个基本术语(HTTPS.SSL.TLS)的含义2. 大致了解 HTTP 和 TCP 的关系(尤其是“短连接”VS“长连接 ...

  8. 浅谈HTTPS和SSL/TLS协议的背景和基础

    相关背景知识要说清楚HTTPS协议的实现原理,至少要需要如下几个背景知识.大致了解几个基础术语(HTTPS.SSL.TLS)的含义大致了解HTTP和TCP的关系(尤其是"短连接"和 ...

  9. 浅谈 HTTPS 和 SSL/TLS 协议的背景与基础

    来自:编程随想   >> 相关背景知识 要说清楚 HTTPS 协议的实现原理,至少需要如下几个背景知识. 大致了解几个基本术语(HTTPS.SSL.TLS)的含义 大致了解 HTTP 和 ...

随机推荐

  1. 第二百五十一节,Bootstrap项目实战--响应式轮播图

    Bootstrap项目实战--响应式轮播图 学习要点: 1.响应式轮播图 本节课我们要在导航条的下方做一张轮播图,自动播放最新的重要动态. 一.响应式轮播图 响应式轮播图 第一步,设置轮播器区域car ...

  2. OGNL支持各种纷繁复杂的表达式

    OGNL支持各种纷繁复杂的表达式.但是最最基本的表达式的原型,是将对象的引用值用点串联起来,从左到右,每一次表达式计算返回的结果成为当前对象,后面部分接着在当前对象上进行计算,一直到全部表达式计算完成 ...

  3. PyQT实现扩展窗口,更多/隐藏

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVcAAAFeCAIAAAC+XMuHAAAgAElEQVR4nOy9Z5Ac153g2fx0F2fiYi ...

  4. 复习及总结--.Net线程篇(4)

    这里要说的就是多线程的锁的问题了 锁:作用在于实现线程间的同步问题,最典型的是售票问题 1,InterLocked 提供的都是静态方法,用来同步对多个共享变量的访问,包括以原子方式递增,递减,比较和替 ...

  5. WPF进阶之接口(1):IValueConverter,IMultiValueConverter

    看一个例子,FontFamily="Trebuchet MS, GlobalSansSerif.CompositeFont" .这样一条简单的语句,熟悉WPF的人在xaml中可能经 ...

  6. 高级service之ipc ADIL用法

    感谢 如果你还没有看过前面一篇文章,建议先去阅读一下 Android Service完全解析,关于服务你所需知道的一切(上) ,因为本篇文章中涉及到的代码是在上篇文章的基础上进行修改的. 在上篇文章中 ...

  7. 教你在Ubuntu上体验Mac风格

    导读 老实说,我是个狂热的 Ubuntu 迷,我喜欢 Ubuntu 默认的 Unity 主题样式外观.此外,还有很多关于 Ubuntu 14.04 的漂亮图标主题样式 可用来美化默认的外观.但正如我上 ...

  8. 1853: [Scoi2010]幸运数字[容斥原理]

    1853: [Scoi2010]幸运数字 Time Limit: 2 Sec  Memory Limit: 64 MBSubmit: 2405  Solved: 887[Submit][Status] ...

  9. Django学习笔记第六篇--实战练习二--简易实现登录注册功能demo

    一.绪论: 简易实现登录功能demo,并没有使用默认身份验证模块,所以做的也很差,关闭了csrf保护,没有认证处理cookie和session,只是简单实现了功能.另外所谓的验证码功能是伪的. 二. ...

  10. 【BZOJ2982】combination Lucas定理

    [BZOJ2982]combination Description LMZ有n个不同的基友,他每天晚上要选m个进行[河蟹],而且要求每天晚上的选择都不一样.那么LMZ能够持续多少个这样的夜晚呢?当然, ...