mqtt paho ssl java端代码
参考链接:http://blog.csdn.net/lingshi210/article/details/52439050
mqtt 的ssl配置可以参阅 
http://houjixin.blog.163.com/blog/static/35628410201432205042955/
然后注意开启防火墙端口。
mqtt的命令和Java端的ssl 必须同时要带上ca.crt、clilent.crt、client.key三个文件,即CA证书、客户证书、客户私钥。
由于java 端不支持client.key的格式,需要命令进行转化
openssl pkcs8 -topk8 -in client.key -out client.pem -nocrypt
另外: 
不知为何ubuntu下关闭防火墙后还是握手失败,cenos下正常,抓包后已经看不到明文了。
Java部分:
1.核心部分只需要设置SSLSocketFactory
MqttConnectOptions options = new MqttConnectOptions();
SSLSocketFactory factory=getSSLSocktet("youpath/ca.crt","youpath/client.crt","youpath/client.pem","password");
options.setSocketFactory(factory);
2.自定义SSLSocketFactory (改进于http://gist.github.com/4104301)
此处的密码应为生成证书的时候输入的密码,未认证。
private 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(caIn,password.toCharArray());
        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());
//      keyIn.close();
        // finally, create SSL socket factory
        SSLContext context = SSLContext.getInstance("TLSv1");
        context.init(kmf.getKeyManagers(),tmf.getTrustManagers(), new SecureRandom());
        return context.getSocketFactory();
    }
Android上会报错,改进如下:
    private 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(KeyStore.getDefaultType());
         caKs.load(null, null);
         caKs.setCertificateEntry("ca-certificate", ca);
         TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
         tmf.init(caKs);
         caIn.close();
        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(caIn,password.toCharArray());
        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(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, password.toCharArray());
//      keyIn.close();
        // finally, create SSL socket factory
        SSLContext context = SSLContext.getInstance("TLSv1");
        context.init(kmf.getKeyManagers(),tmf.getTrustManagers(), new SecureRandom());
        return context.getSocketFactory();
    }
3.获取私钥代码部分
由于只能读取PKCS8的格式,所以需要转成pem
    public 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);  
    } 
附录:
package com;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
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.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import org.apache.commons.codec.binary.Base64;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.internal.security.SSLSocketFactoryFactory;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class Server extends JFrame {
    private static final long serialVersionUID = 1L;
    private JPanel panel;
    private JPanel panelText;
    private JPanel panelText2;
    private JButton button;
    private JButton button2;
    private JButton subscribeButton;
    private JTextArea textHost;
    private JTextArea textClientID;
    private JTextArea textPublishMsg;
    private JTextArea textTopic;
    private MqttClient client;
    private String host = "ssl://192.168.10.233:1883";
    private MqttTopic topic;
    private MqttMessage message;
    private String userToken = "999999";
    private String myTopicRoot = "test";
    private String myTopic = null;
    private String clienID = "test1234567";
    public Server() {
        Container container = this.getContentPane();
        panel = new JPanel();
        panelText = new JPanel();
        panelText2 = new JPanel();
        button = new JButton("发布主题消息");
        button2 = new JButton("更换客户机地址和IP");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                try {
                    host = textHost.getText();
                    clienID = textClientID.getText();
                    if (client == null) {
                        client = new MqttClient(host, clienID, new MemoryPersistence());
                    }
                    if (!client.isConnected()) {
                        connect();
                    }
                    publishMsg(textTopic.getText(), textPublishMsg.getText());
                } catch (Exception e) {
                    e.printStackTrace();
                    showErrorMsg(e.toString());
                }
            }
        });
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                host = textHost.getText();
                clienID = textClientID.getText();
                try {
                    if (client != null)
                        client.disconnectForcibly();
                    client = new MqttClient(host, clienID, new MemoryPersistence());
                    connect();
                } catch (Exception e) {
                    e.printStackTrace();
                    showErrorMsg(e.toString());
                }
            }
        });
        subscribeButton = new JButton("订阅主题");
        subscribeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                try {
                    if (client == null) {
                        client = new MqttClient(host, clienID, new MemoryPersistence());
                    }
                    if (!client.isConnected()) {
                        connect();
                    }
                    if (myTopic != null && !myTopic.equals(textTopic.getText())) {
                        client.subscribe(myTopic);
                    }
                    client.subscribe(textTopic.getText());
                    myTopic = textTopic.getText();
                } catch (Exception e) {
                    e.printStackTrace();
                    showErrorMsg(e.toString());
                }
            }
        });
        textHost = new JTextArea();
        textHost.setText(host);
        textClientID = new JTextArea();
        textClientID.setText(clienID);
        panel.add(button);
        panel.add(subscribeButton);
        panelText.add(button2);
        panelText.add(new JLabel("mqtt地址"));
        panelText.add(textHost);
        panelText.add(new JLabel("ClienId"));
        panelText.add(textClientID);
        panelText.add(new JLabel("主题"));
        textTopic = new JTextArea();
        textTopic.setText(myTopicRoot);
        panelText.add(textTopic);
        textPublishMsg = new JTextArea();
        textPublishMsg.setText("@" + userToken + "@E@5@" + userToken + "@");
        panelText2.add(new JLabel("mqtt消息"));
        panelText2.add(textPublishMsg);
        container.add(panel, BorderLayout.NORTH);
        container.add(panelText, BorderLayout.CENTER);
        container.add(panelText2, BorderLayout.SOUTH);
        // try {
        // client = new MqttClient(host, clienID,
        // new MemoryPersistence());
        // connect();
        // } catch (Exception e) {
        // showErrorMsg(e.toString());
        // }
    }
    private 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(caIn,password.toCharArray());
        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());
//      keyIn.close();
        // finally, create SSL socket factory
        SSLContext context = SSLContext.getInstance("TLSv1");
        context.init(kmf.getKeyManagers(),tmf.getTrustManagers(), new SecureRandom());
        return context.getSocketFactory();
    }
    private 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();
    }
    public 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 void connect() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        // options.setUserName(userName);
        // options.setPassword(passWord.toCharArray());
        // 设置超时时间
        // options.setConnectionTimeout(10);
        // 设置会话心跳时间
        // options.setKeepAliveInterval(20);
        // try {
        // options.setWill("willtest", "SENDgpslost".getBytes(), 1, false);
        // } catch (Exception e1) {
        // // TODO Auto-generated catch block
        // System.out.print(e1);
        // }
        try {
            if (!SSLSocketFactoryFactory.isSupportedOnJVM()) {
                System.out.print("isSupportedOnJVM=false");
            }
            SSLSocketFactory factory=getSSLSocktet("F:/ssl/ca.crt","F:/ssl/client.crt","F:/ssl/client.pem","brt123");
            options.setSocketFactory(factory);
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("connectionLost-----------");
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("deliveryComplete---------" + token.isComplete());
                }
                @Override
                public void messageArrived(String topic, MqttMessage arg1) throws Exception {
                    System.out.println("messageArrived----------");
                    String msg = new String(arg1.getPayload());
                    showErrorMsg("主题:" + topic + "\r\n消息:" + msg);
                }
            });
            topic = client.getTopic(myTopicRoot + userToken);
            client.connect(options);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void publishMsg(String topoc, String msg) {
        message = new MqttMessage();
        message.setQos(0);
        message.setRetained(false);
        System.out.println(message.isRetained() + "------ratained状态");
        try {
            message.setPayload(msg.getBytes("UTF-8"));
            client.publish(topoc, message);
        } catch (Exception e) {
            e.printStackTrace();
            showErrorMsg(e.toString());
        }
    }
    private void showErrorMsg(String msg) {
        JOptionPane.showMessageDialog(null, msg);
    }
}												
											mqtt paho ssl java端代码的更多相关文章
- IOS IAP APP内支付 Java服务端代码
		
IOS IAP APP内支付 Java服务端代码 场景:作为后台需要为app提供服务,在ios中,app内进行支付购买时需要进行二次验证. 基础:可以参考上一篇转载的博文In-App Purcha ...
 - mqtt协议实现 java服务端推送功能(三)项目中给多个用户推送功能
		
接着上一篇说,上一篇的TOPIC是写死的,然而在实际项目中要给不同用户 也就是不同的topic进行推送 所以要写活 package com.fh.controller.information.push ...
 - openssl实现双向认证教程(服务端代码+客户端代码+证书生成)
		
一.背景说明 1.1 面临问题 最近一份产品检测报告建议使用基于pki的认证方式,由于产品已实现https,商量之下认为其意思是使用双向认证以处理中间人形式攻击. <信息安全工程>中接触过 ...
 - iOS 基于APNS消息推送原理与实现(包括JAVA后台代码)
		
Push的原理: Push 的工作机制可以简单的概括为下图 图中,Provider是指某个iPhone软件的Push服务器,这篇文章我将使用.net作为Provider. APNS 是Apple ...
 - 基于mosquitto的MQTT服务器---SSL/TLS 单向认证+双向认证
		
基于mosquitto的MQTT服务器---SSL/TLS 单向认证+双向认证 摘自:https://blog.csdn.net/ty1121466568/article/details/811184 ...
 - netty实现websocket客户端(附:测试服务端代码)
		
1,客户端启动类 package test3; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.Unpooled; import ...
 - phpCAS::handleLogoutRequests()关于java端项目登出而php端项目检测不到的测试
		
首先,假如你有做过cas,再假如你的cas里面有php项目,这个时候要让php项目拥有cas的sso功能,你需要改造你的项目,由于各人的项目不同,但是原理差不多,都是通过从cas服务器获取sessio ...
 - Flex 对Java端返回Collection的处理方法
		
将Flex与Spring集成后(BlazeDS 与Spring集成指南 ),第一个面临的问题就是:对于Java端返回的各种Java类型的对象,Flex中能否有相应的数据类型来映射. 处理,尤其是Lis ...
 - android NDK 实用学习(三)- java端类对象的构造及使用
		
1,读此文章前我假设你已经读过: android NDK 实用学习-获取java端类及其类变量 android NDK 实用学习-java端对象成员赋值和获取对象成员值 2,java端类对象的构造: ...
 
随机推荐
- unix命令
			
最近需要用到一些Unix的东西 ,就学习了下这个东西,简单记录下命令,方便以后查询! 1. ls这是最基本的档案指令. ls 的意义为 "list",也就是将某一个目录或是某一个档 ...
 - c++趣味之shared_ptr额外好处
			
shared_ptr(sp)额外好处是什么?即使被转为基类,析构函数也可以正常执行. 已知两个类 class foo{}; class bar:foo{public:~bar(){}}; 先来看不用s ...
 - susmote个人网站博客论坛(TexTec | 关注互联网技术,传播极客精神)
			
网站地址 www.susmote.com www.textec.club 欢迎您的访问
 - Linux开发环境工具收集
			
zsh & oh-my-zsh 配置oh-my-zsh之前要先安装Git sudo apt-get install zsh sudo apt-get install git wget http ...
 - Lombok介绍、使用方法和总结
			
1 Lombok背景介绍 官方介绍如下: Project Lombok makes java a spicier language by adding 'handlers' that know how ...
 - poj-1056-IMMEDIATE DECODABILITY(字典)
			
Description An encoding of a set of symbols is said to be immediately decodable if no code for one s ...
 - 【Python】 配置文件相对路径&软件自动执行的工作目录
			
今天对监控脚本做了一些变更,然后突然发现监控全部都失效了..排查了半天问题仍然不知所踪.最终发现居然是一个踩过好几次的老坑.. 就是脚本内写的配置文件为了调试方便写成了相对路径,但是在上线时没有意识到 ...
 - 对于一个刚入门的linux运维来说
			
干 就完了~ 我觉得 人生的意义在于 不断地学习......
 - Oracle查询优化改写--------------------范围处理
			
一.定位连续值的范围 二.查找同一组或分区中行之间的差
 - (Matlab)GPU计算及CPU计算能力的比较
			
%%首先以200*200的矩阵做加减乘除 做比较 t = zeros(1,100); A = rand(200,200);B = rand(200,200);C = rand(200,200); fo ...