emqtt 试用(八)ssl认证 - 代码验证
参考链接:http://emqtt.com/clients#java
http://docs.emqtt.cn/zh_CN/latest/config.html#mqtt-ssl-8883
一、单向认证
1、配置
## SSL Options
listener.ssl.external.handshake_timeout = 15
listener.ssl.external.keyfile = etc/certs/server-key.pem
listener.ssl.external.certfile = etc/certs/server-cert.pem
## 开启双向认证
## listener.ssl.external.cacertfile = etc/certs/rootca-cert.pem
## listener.ssl.external.verify = verify_peer
## listener.ssl.external.fail_if_no_peer_cert = true
2、代码
将 cacert.pem 重命名为 rootca-cert.crt
加入JDK证书信任,jdk1.8.0_121\jre\lib\security目录下运行命令:
keytool -import -alias cacert -keystore cacerts -file 盘:目录/rootca-cert.crt
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.cert.CertificateException;
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.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttPublishSample {
public static void main(String[] args) throws KeyManagementException, CertificateException, FileNotFoundException, IOException, KeyStoreException {
String topic = "MQTT Examples";
String content = "Message from MqttPublishSample";
int qos = 2;
String broker = "ssl://10.110.111.251:8883";
String clientId = "JavaSample";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
System.out.println("Connecting to broker: "+broker);
sampleClient.connect(connOpts);
System.out.println("Connected");
System.out.println("Publishing message: "+content);
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos);
sampleClient.publish(topic, message);
System.out.println("Message published");
sampleClient.disconnect();
System.out.println("Disconnected");
System.exit(0);
} catch(MqttException me) {
System.out.println("reason "+me.getReasonCode());
System.out.println("msg "+me.getMessage());
System.out.println("loc "+me.getLocalizedMessage());
System.out.println("cause "+me.getCause());
System.out.println("excep "+me);
me.printStackTrace();
}
}
}
二、双向认证
1、配置
## SSL Options
listener.ssl.external.handshake_timeout = 15
listener.ssl.external.keyfile = etc/certs/server-key.pem
listener.ssl.external.certfile = etc/certs/server-cert.pem
## 开启双向认证
listener.ssl.external.cacertfile = etc/certs/cacert.pem
listener.ssl.external.verify = verify_peer
listener.ssl.external.fail_if_no_peer_cert = true
2、代码
证书转换,将 client-key.pem 转换成 pkcs8 格式的证书
openssl pkcs8 -topk8 -inform PEM -in client-key.pem -outform PEM -nocrypt -out client-key-pkcs8.pem
将 cacert.pem 重命名为 rootca-cert.crt
将 client-cert.pem 重命名为 client-cert.crt
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import org.apache.commons.codec.binary.Base64;
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.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class PahoTlsExample {
private static void connect() {
String topic = "MQTT Examples";
String content = "Message from MqttPublishSample";
int qos = 2;
String broker = "ssl://10.110.111.251:8883";
String clientId = "JavaSample";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
SSLSocketFactory factory = null;
try {
factory = getSSLSocktet("F:/emq/cacert/cacert.crt","F:/emq/cacert/client-cert.crt","F:/emq/cacert/client-key-pkcs8.pem","brt123");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connOpts.setSocketFactory(factory);
System.out.println("Connecting to broker: "+broker);
sampleClient.connect(connOpts);
System.out.println("Connected");
System.out.println("Publishing message: "+content);
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos);
sampleClient.publish(topic, message);
System.out.println("Message published");
sampleClient.disconnect();
System.out.println("Disconnected");
System.exit(0);
} catch(MqttException me) {
System.out.println("reason "+me.getReasonCode());
System.out.println("msg "+me.getMessage());
System.out.println("loc "+me.getLocalizedMessage());
System.out.println("cause "+me.getCause());
System.out.println("excep "+me);
me.printStackTrace();
}
}
private static SSLSocketFactory getSSLSocktet(String caPath,String crtPath, String keyPath, String password) throws Exception {
// CA certificate is used to authenticate server
CertificateFactory cAf = CertificateFactory.getInstance("X.509");
FileInputStream caIn = new FileInputStream(caPath);
X509Certificate ca = (X509Certificate) cAf.generateCertificate(caIn);
KeyStore caKs = KeyStore.getInstance("JKS");
caKs.load(null, null);
caKs.setCertificateEntry("ca-certificate", ca);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(caKs);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream crtIn = new FileInputStream(crtPath);
X509Certificate caCert = (X509Certificate) cf.generateCertificate(crtIn);
crtIn.close();
// 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", caCert);
ks.setKeyEntry("private-key", getPrivateKey(keyPath), password.toCharArray(),
new java.security.cert.Certificate[]{caCert} );
KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
kmf.init(ks, password.toCharArray());
// finally, create SSL socket factory
SSLContext context = SSLContext.getInstance("TLSv1");
context.init(kmf.getKeyManagers(),tmf.getTrustManagers(), new SecureRandom());
return context.getSocketFactory();
}
public static PrivateKey getPrivateKey(String path) throws Exception{
org.apache.commons.codec.binary.Base64 base64=new Base64();
byte[] buffer= base64.decode(getPem(path));
PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory= KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
}
private static String getPem(String path) throws Exception{
FileInputStream fin=new FileInputStream(path);
BufferedReader br= new BufferedReader(new InputStreamReader(fin));
String readLine= null;
StringBuilder sb= new StringBuilder();
while((readLine= br.readLine())!=null){
if(readLine.charAt(0)=='-'){
continue;
}else{
sb.append(readLine);
sb.append('\r');
}
}
fin.close();
return sb.toString();
}
}
emqtt 试用(八)ssl认证 - 代码验证的更多相关文章
- SSL握手通信详解及linux下c/c++ SSL Socket代码举例(另附SSL双向认证客户端代码)
SSL握手通信详解及linux下c/c++ SSL Socket代码举例(另附SSL双向认证客户端代码) 摘自: https://blog.csdn.net/sjin_1314/article/det ...
- openssl制作双向认证经过验证可行
openssl制作双向认证经过验证可行 http://www.360doc.com/content/12/0524/15/2150778_213390447.shtml 2012-05-24 履历馆 ...
- java中 SSL认证和keystore使用
java中 SSL认证和keystore使用 2013-10-12 11:08 10488人阅读 评论(0) 收藏 举报 目录(?)[+] 好久没用过SSL认证了,东西久不用,就有点生疏. ...
- Django基础八之认证模块---auth
Django基础八之认证模块---auth 目录 Django基础八之认证模块---auth 1. auth介绍 2. autho常用操作 2.1 创建用户 2.2 验证用户 2.3 验证用户是否登录 ...
- Tomcat 实现双向SSL认证
大概思路: 使用openssl生产CA证书,使用keytool生产密钥库 实验环境:RHEL6.4+Tomcat8 一.生成CA根证书,并自签名 1.生成CA密钥 # genrsa [产生密钥命令] ...
- ssl/https双向验证的配置
1.SSL认证 不需要特别配置,相关证书库生成看https认证中的相关部分 2.HTTPS认证 一.基本概念 1.单向认证,就是传输的数据加密过了,但是不会校验客户端的来源 2.双向认证,如果客户端 ...
- ssl https双向验证的配置与证书库的生成
1.SSL认证 不须要特别配置,相关证书库生成看https认证中的相关部分 2.HTTPS认证 一.基本概念 1.单向认证,就是传输的数据加密过了,可是不会校验client的来源 2.双向认证,假设 ...
- RSA原理、ssl认证、Tomcat中配置数字证书以及网络传输数据中的密码学知识
情形一:接口的加.解密与加.验签 rsa不是只有加密解密,除此外还有加签和验签.之前一直误以为加密就是加签,解密就是验签.这是错误的! 正确的理解是: 数据传输的机密性:公钥加密私钥解密是密送,保 ...
- Apollo单向SSL认证(1)
参考链接:https://www.cnblogs.com/benwu/articles/4891758.html keytool -genkey -alias mybroker -keyalg RSA ...
随机推荐
- 【转】UML的9种图例解析
UML图中类之间的关系:依赖,泛化,关联,聚合,组合,实现 类与类图 1) 类(Class)封装了数据和行为,是面向对象的重要组成部分,它是具有相同属性.操作.关系的对象集合的总称. 2) 在系统中, ...
- Python爬虫获取异步加载站点pexels并下载图片(Python爬虫实战3)
1. 异步加载爬虫 对于静态页面爬虫很容易获取到站点的数据内容,然而静态页面需要全量加载站点的所有数据,对于网站的访问和带宽是巨大的挑战,对于高并发和大访问访问量的站点来说,需要使用AJAX相关的技术 ...
- 对thinkphp的命名空间的理解
tp的命名空间其实就是虚拟目录,目的是为了自动加载类(不是管理文件) tp命名空间包含两部分: (1)初始命名空间:Library (2)根命名空间: a)Library文件下的所有文件夹,只含一级文 ...
- redis分片和哨兵
1 Redis的使用 1.1 Redis入门案例 1.1.1 什么样的数据使用缓存 说明:使用缓存其实为了减少用户查询数据库的时间.如果数据频繁的变更.不适用缓存.缓存中的数据应该保存修改频率不高的数 ...
- firemonkey EDit 改变颜色
PS:本来不应该有多难,结果折腾了半天, firemonkey EDit Canvas 按需绘颜色 procedure TForm.EditPaint(Sender: TObject; Canvas ...
- iTerm2设置及使用
1. 安装 iTerm2 下载地址:https://www.iterm2.com/downloads.html 下载的是压缩文件,解压后是执行程序文件,你可以直接双击,或者直接将它拖到 Applica ...
- Spark ML源码分析之二 从单机到分布式
前一节从宏观角度给大家介绍了Spark ML的设计框架(链接:http://www.cnblogs.com/jicanghai/p/8570805.html),本节我们将介绍,Spar ...
- 【Zabbix】大规模监控误报发生时的处理方案
今天遇到了这样一件事..Zabbix一直在用的数据库突然间崩溃,无法连接了.在down掉的那一时刻开始,zabbix向管理员报了警.然后随之而来的是铺天盖地的所有主机zabbix agent无法连接的 ...
- redis备份与恢复
1.redis的备份 redis需要远程访问 添加密码进行登录,修改主配置文件添加:requirepass xxx redis-cli -h 127.0.0.1 -p 6379 -a 123456 b ...
- c#多线程,进度条,实时给前台发送数据
///做了一个wpf多线程,在实际场景中利用多线程保证程序不会卡死,性能上有所提高 //启动线程处理 Thread thread1 = new Thread(Update ...