参考链接: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认证 - 代码验证的更多相关文章

  1. SSL握手通信详解及linux下c/c++ SSL Socket代码举例(另附SSL双向认证客户端代码)

    SSL握手通信详解及linux下c/c++ SSL Socket代码举例(另附SSL双向认证客户端代码) 摘自: https://blog.csdn.net/sjin_1314/article/det ...

  2. openssl制作双向认证经过验证可行

    openssl制作双向认证经过验证可行 http://www.360doc.com/content/12/0524/15/2150778_213390447.shtml 2012-05-24  履历馆 ...

  3. java中 SSL认证和keystore使用

    java中 SSL认证和keystore使用 2013-10-12 11:08 10488人阅读 评论(0) 收藏 举报   目录(?)[+]     好久没用过SSL认证了,东西久不用,就有点生疏. ...

  4. Django基础八之认证模块---auth

    Django基础八之认证模块---auth 目录 Django基础八之认证模块---auth 1. auth介绍 2. autho常用操作 2.1 创建用户 2.2 验证用户 2.3 验证用户是否登录 ...

  5. Tomcat 实现双向SSL认证

    大概思路: 使用openssl生产CA证书,使用keytool生产密钥库 实验环境:RHEL6.4+Tomcat8 一.生成CA根证书,并自签名 1.生成CA密钥 # genrsa [产生密钥命令] ...

  6. ssl/https双向验证的配置

    1.SSL认证 不需要特别配置,相关证书库生成看https认证中的相关部分 2.HTTPS认证 一.基本概念 1.单向认证,就是传输的数据加密过了,但是不会校验客户端的来源  2.双向认证,如果客户端 ...

  7. ssl https双向验证的配置与证书库的生成

    1.SSL认证 不须要特别配置,相关证书库生成看https认证中的相关部分 2.HTTPS认证 一.基本概念 1.单向认证,就是传输的数据加密过了,可是不会校验client的来源  2.双向认证,假设 ...

  8. RSA原理、ssl认证、Tomcat中配置数字证书以及网络传输数据中的密码学知识

      情形一:接口的加.解密与加.验签 rsa不是只有加密解密,除此外还有加签和验签.之前一直误以为加密就是加签,解密就是验签.这是错误的! 正确的理解是: 数据传输的机密性:公钥加密私钥解密是密送,保 ...

  9. Apollo单向SSL认证(1)

    参考链接:https://www.cnblogs.com/benwu/articles/4891758.html keytool -genkey -alias mybroker -keyalg RSA ...

随机推荐

  1. Spring整合Shiro并扩展使用EL表达式

    Shiro是一个轻量级的权限控制框架,应用非常广泛.本文的重点是介绍Spring整合Shiro,并通过扩展使用Spring的EL表达式,使@RequiresRoles等支持动态的参数.对Shiro的介 ...

  2. .NET Core开源API网关 – Ocelot中文文档

    Ocelot是一个用.NET Core实现并且开源的API网关,它功能强大,包括了:路由.请求聚合.服务发现.认证.鉴权.限流熔断.并内置了负载均衡器与Service Fabric.Butterfly ...

  3. C和C#的区别

    c:面向过程,语法太麻烦,但对硬件的底层编程和对内存的管理的灵活性方面c是其他高级语言所不可及的. c#:纯面向对象的(跟java很像如果你对java了解估计你就会明白c&c#之间的区别了), ...

  4. TLA+和并发系统正确性验证

    TLA+介绍 TLA+(WIKI,官网)是一门领域特定语言,主要用于数理逻辑计算和并发系统的正确性验证.TLA+中的TLA代表的是"行为时序逻辑(Temporal Logic of Acti ...

  5. Docker国内镜像源设置

    编辑json文件,添加如下内容后重启docker即可. [root@Docker ~]# cat /etc/docker/daemon.json{ "registry-mirrors&quo ...

  6. canvas实现将文字变成颗粒

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  7. C++string类总结

    一.string的初始化 首先,为了在程序中使用string类型,必须包含头文件 <string>.如下: #include <string> 注意这里不是string.h,s ...

  8. X509证书认证流程介绍

    X509证书介绍X.509 是由国际电信联盟(ITU-T)制定的数字证书标准,相信这是人尽皆知的了,目前X.509证书据我所知有三个版本,.net中使用的是x.509-2,X.509-2 版引入了主体 ...

  9. Linux 如何使用echo指令向文件写入内容

    0.前言     本文总结如何使用echo命令向文件中写入内容,例如使用echo指令覆盖文件内容,使用echo指令向文件追加内容,使用echo指令往文件中追加制表符.     echo向文件中输出内容 ...

  10. 由浅入深理解----java反射技术

    java反射机制详解 java反射机制是在运行状态下,对任意一个类可以获取该类的属性和方法,对任意一个对象可以调用其属性和方法.这种动态的获取信息和调用对象的方法的功能称为java的反射机制 clas ...