org.eclipse.paho.client.mqttv3 使用 Apache Mq 实现mqtt协议 双向加密

时间:2024-03-25 20:28:34

1.参考apache生成证书http://activemq.apache.org/how-do-i-use-ssl.html

org.eclipse.paho.client.mqttv3 使用 Apache Mq 实现mqtt协议 双向加密

生成broker.ks、 broker.ts与client.ks、 client.ts

ks即:keystore缩写,存放私钥,关联的证书或证书链

ts即:truststore缩写,存放客户端信任的证书(公钥)

 

 

2.配置activeMq broker 

将broker.ks    broker.ts 上传至服务器,与activemq.xml同一个目录下

修改activeMq.xml文件,

  <broker>  </broker> 内添加以下内容

<sslContext>
          <sslContext keyStore="file:${activemq.base}/conf/broker.ks"
                      keyStorePassword="123456"
                      trustStore="file:${activemq.base}/conf/client.ks"
                      trustStorePassword="123456"
                      />
        </sslContext>


修改mqtt 的连接方式如下:

 

org.eclipse.paho.client.mqttv3 使用 Apache Mq 实现mqtt协议 双向加密

 

 服务器配置完成,

 

java代码中MqttConnectOptions 设置ssl 配置如下,JKS 是keyStore 的类型,使用jdk生成的都是JKS 类型的

 

client = new MqttClient("ssl://localhost:1883", "Session_3");
connOpt = new MqttConnectOptions();
connOpt.setCleanSession(true);

Properties sslProperties = new Properties();

sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORE, 
"/home/KeyStore.jks");
sslProperties.put(SSLSocketFactoryFactory.TRUSTSTOREPWD, "123456");
sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORETYPE, "JKS");
sslProperties.put(SSLSocketFactoryFactory.CLIENTAUTH, true);

sslProperties.put(SSLSocketFactoryFactory.KEYSTORE, 
"/home/clientStore.jks");
sslProperties.put(SSLSocketFactoryFactory.KEYSTOREPWD, "123456");
sslProperties.put(SSLSocketFactoryFactory.KEYSTORETYPE, "JKS");


connOpt.setSSLProperties(sslProperties);

client.connect(connOpt);

client.subscribe("sample_T");

client.setCallback( new MQTTSampleSubscriber() );

至此,ssl双向加密完成