emq安装使用 以及ssl单向双向验证及代码实现 小白使用手册

阅读: 评论:0

emq安装使用 以及ssl单向双向验证及代码实现 小白使用手册

emq安装使用 以及ssl单向双向验证及代码实现 小白使用手册

目录

1 openssl安装

2 emq安装

3 ssl创建证书

4 ssl双向验证和单向验证ssl配置

5 代码实现

6 mqtt命令


1 openssl安装

opensll emq安装包及客户端下载路径

opensslemqx-ubuntu16.4ActivePerl-5.28.1emqx-windows-v4.1.1.-互联网文档类资源-CSDN下载

用于证书生产

$ tar zxf openssl openssl-1.0.

$ cd openssl-1.0.1

$ ./config --prefix=/usr/local

 我记得执行到这就可以了,openssl version 可查看版本
$ make

$ make clean

$ sudo make install


2 emq安装

emqx-ubuntu16.04-v4.1.1_amd64.deb 安装

sudo dpkg -i emqx-ubuntu16.04-v4.1.1_amd64.deb

自动安装在 /etc/emqx 目录下;修改f需要知道

客户端连接端口默认:18083  admin public
ssl默认端口为8883,具体可以查看f

3 ssl创建证书

3.1准备工作

在opt目录下创建ssl目录用来临时存储生成的证书文件
mkdir /opt/ssl
cd /opt/ssl/

生成证书索引库数据库文件
touch demoCA/
touch
touch demoCA/serial

指定第一个颁发证书的序列号
echo 01 > demoCA/serial

3.2 证书生成

3.2.1 CA证书生成
openssl req -x509 -new -days 3650 -keyout ca.key - -nodes
openssl req -x509 -new -days 3650 -keyout ca.key - -nodes
参数:
Country Name (2 letter code) [XX]:国家【中国---CN】
State or Province Name (full name) []:省份
Locality Name (eg, city) [Default City]:城市
Organization Name (eg, company) [Default Company Ltd]:组织名称
Organizational Unit Name (eg, section) []:组织单元名称
Common Name (eg, your name or your server's hostname) []:服务器IP
Email Address []: 邮箱地址


3.2.2 为server端生成证书
1生成私钥
openssl genrsa -out server.key 2048
2生成证书请求csr文件
openssl req -new -key server.key -out server.csr
参数填写与前面类似
A challenge password []: 密码
An optional company name []:公司名称
3生成证书
openssl ca -in server.csr - - -keyfile ca.key -days 3650

3.2.3 为Client端生成证书
1生成私钥
openssl genrsa -out client.key 2048
2生成证书请求:
openssl req -new -key client.key -out client.csr
参数与服务端证书生成类似,不过这里我用到ip是客户端ip
3生成证书
openssl ca -in client.csr - - -keyfile ca.key


4 ssl双向验证和单向验证ssl配置

修改 f文件

4.1单向认证
## SSL Options
al.handshake_timeout = 15
al.keyfile = etc/certs/server-key.pem
al.certfile = etc/certs/server-cert.pem

## 开启双向认证
## al.cacertfile = etc/certs/rootca-cert.pem
## al.verify = verify_peer
## al.fail_if_no_peer_cert = true


4.2 双向认证
## SSL Options
al.handshake_timeout = 15
al.keyfile = etc/certs/server-key.pem
al.certfile = etc/certs/server-cert.pem

## 开启双向认证
al.cacertfile = etc/certs/cacert.pem
al.verify = verify_peer
al.fail_if_no_peer_cert = true

5 代码实现

 1 pom 依赖

   <dependency><groupId>org.bouncycastle</groupId><artifactId>bcpkix-jdk15on</artifactId><version>1.47</version></dependency> 

 2 建立连接时赋值进行如下处理:

MqttConnectOptions  mqttConnectOptions = new MqttConnectOptions();
//mqtt 建立连接时赋值 双向mqttConnectOptions.SocketFactory(rootCrtPath, 
clientCrtPath, clientKeyPath, clientPassword));//单向         	mqttConnectOptions.SocketFactorySingle(rootCrtPath));

3 加载证书工具类实现

import javax.ssl.SSLSocketFactory;import java.security.Security;import javax.ssl.KeyManagerFactory;
import javax.ssl.SSLContext;
import javax.ssl.TrustManagerFactory;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.SecureRandom;
import X509Certificate;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 certificatePEMReader reader = new PEMReader(new InputStreamReader(new (caCrtFile)))));X509Certificate caCert = (adObject();reader.close();// load client certificatereader = new PEMReader(new InputStreamReader(new (crtFile)))));X509Certificate cert = (adObject();reader.close();// load client private keyreader = new PEMReader(new InputStreamReader(new (keyFile)))),new PasswordFinder() {@Overridepublic char[] getPassword() {CharArray();}});KeyPair key = (adObject();reader.close();// CA certificate is used to authenticate serverKeyStore caKs = DefaultType());caKs.load(null, null);caKs.setCertificateEntry("ca-certificate", caCert);TrustManagerFactory tmf = DefaultAlgorithm());tmf.init(caKs);// client key and certificates are sent to server so it can authenticate usKeyStore ks = DefaultType());ks.load(null, null);ks.setCertificateEntry("certificate", cert);ks.setKeyEntry("private-key", Private(), CharArray(), new Certificate[]{cert});KeyManagerFactory kmf = DefaultAlgorithm());kmf.init(ks, CharArray());// finally, create SSL socket factorySSLContext context = Instance("TLSv1.1");context.KeyManagers(), TrustManagers(), null);SocketFactory();}public static SSLSocketFactory getSocketFactorySingle(final String caCrtFile) throws Exception {Security.addProvider(new BouncyCastleProvider());// load CA certificatePEMReader reader = new PEMReader(new InputStreamReader(new (caCrtFile)))));X509Certificate caCert = (adObject();reader.close();// CA certificate is used to authenticate server
//			KeyStore caKs = DefaultType());
//			caKs.load(null, null);
//			caKs.setCertificateEntry("ca-certificate", caCert);//TrustManagerFactory tmf = DefaultAlgorithm());//tmf.init(caKs);// client key and certificates are sent to server so it can authenticate usKeyStore ks = DefaultType());//"JKS"ks.load(null, null);ks.setCertificateEntry("ca-certificate", caCert);TrustManagerFactory tmf = DefaultAlgorithm());//"PKIX"tmf.init(ks);// finally, create SSL socket factorySSLContext context = Instance("TLSv1.1");context.init(null, TrustManagers(), new SecureRandom());//----------------------------------------------------------------
//			 CertificateFactory cAf = Instance("X.509");
//		        FileInputStream caIn = new FileInputStream(caPath);
//		        X509Certificate ca = (X509Certificate) ateCertificate(caIn);
//		        KeyStore caKs = Instance("JKS");
//		        caKs.load(null, null);
//		        caKs.setCertificateEntry("ca-certificate", ca);
//		        TrustManagerFactory tmf = Instance("PKIX");
//		        tmf.init(caKs);
//		 
//		      
//		        SSLContext context = Instance("TLSv1");
//		        context.init(null, TrustManagers(), new SecureRandom());
//		 
//		        SocketFactory();SocketFactory();}
}

6 mqtt命令

Usage: emqx_ctl
--------------------------------------------------------------------------------------------------------------
mgmt list                                                             # List Applications
mgmt insert <AppId> <Name>                                            # Add Application of REST API
mgmt update <AppId> <status>                                          # Update Application of REST API
mgmt lookup <AppId>                                                   # Get Application of REST API
mgmt delete <AppId>                                                   # Delete Application of REST API
--------------------------------------------------------------------------------------------------------------
status                                                                # Show broker status
--------------------------------------------------------------------------------------------------------------
broker                                                                # Show broker version, uptime and description
broker stats                                                          # Show broker statistics of clients, topics, subscribers
broker metrics                                                        # Show broker metrics
--------------------------------------------------------------------------------------------------------------
cluster join <Node>                                                   # Join the cluster
cluster leave                                                         # Leave the cluster
cluster force-leave <Node>                                            # Force the node leave from cluster
cluster status                                                        # Cluster status
--------------------------------------------------------------------------------------------------------------
clients list                                                          # List all clients
clients show <ClientId>                                               # Show a client
clients kick <ClientId>                                               # Kick out a client
--------------------------------------------------------------------------------------------------------------
routes list                                                           # List all routes
routes show <Topic>                                                   # Show a route
--------------------------------------------------------------------------------------------------------------
subscriptions list                                                    # List all subscriptions
subscriptions show <ClientId>                                         # Show subscriptions of a client
subscriptions add <ClientId> <Topic> <QoS>                            # Add a static subscription manually
subscriptions del <ClientId> <Topic>                                  # Delete a static subscription manually
--------------------------------------------------------------------------------------------------------------
plugins list                                                          # Show loaded plugins
plugins load <Plugin>                                                 # Load plugin
plugins unload <Plugin>                                               # Unload plugin
plugins reload <Plugin>                                               # Reload plugin
--------------------------------------------------------------------------------------------------------------
vm all                                                                # Show info of Erlang VM
vm load                                                               # Show load of Erlang VM
vm memory                                                             # Show memory of Erlang VM
vm process                                                            # Show process of Erlang VM
vm io                                                                 # Show IO of Erlang VM
vm ports                                                              # Show Ports of Erlang VM
--------------------------------------------------------------------------------------------------------------
mnesia                                                                # Mnesia system info
--------------------------------------------------------------------------------------------------------------
log set-level <Level>                                                 # Set the overall log level
log primary-level                                                     # Show the primary log level now
log primary-level <Level>                                             # Set the primary log level
log handlers list                                                     # Show log handlers
log handlers start <HandlerId>                                        # Start a log handler
log handlers stop  <HandlerId>                                        # Stop a log handler
log handlers set-level <HandlerId> <Level>                            # Set log level of a log handler
--------------------------------------------------------------------------------------------------------------
trace list                                                            # List all traces started
trace start client <ClientId> <File> [<Level>]                        # Traces for a client
trace stop  client <ClientId>                                         # Stop tracing for a client
trace start topic  <Topic>    <File> [<Level>]                        # Traces for a topic
trace stop  topic  <Topic>                                            # Stop tracing for a topic
--------------------------------------------------------------------------------------------------------------
listeners                                                             # List listeners
listeners stop    <Identifier>                                        # Stop a listener
listeners stop    <Proto> <Port>                                      # Stop a listener
listeners restart <Identifier>                                        # Restart a listener
--------------------------------------------------------------------------------------------------------------
data import <File> [--env '<json>']                                   # Import data from the specified file, possibly with overrides
data export                                                           # Export data
--------------------------------------------------------------------------------------------------------------
acl cache-clean all                                                   # Clears acl cache on all nodes
acl cache-clean node <Node>                                           # Clears acl cache on given node
acl cache-clean <ClientId>                                            # Clears acl cache for given client
--------------------------------------------------------------------------------------------------------------
admins add <Username> <Password> <Tags>                               # Add dashboard user
admins passwd <Username> <Password>                                   # Reset dashboard user password
admins del <Username>                                                 # Delete dashboard user
--------------------------------------------------------------------------------------------------------------
recon memory                                                          # recon_alloc:memory/2
recon allocated                                                       # recon_alloc:memory(allocated_types, current|max)
recon bin_leak                                                        # recon:bin_leak(100)
recon node_stats                                                      # recon:node_stats(10, 1000)
recon remote_load Mod                                                 # recon:remote_load(Mod)
recon proc_count Attr N                                               # recon:proc_count(Attr, N)
--------------------------------------------------------------------------------------------------------------
retainer info                                                         # Show the count of retained messages
retainer topics                                                       # Show all topics of retained messages
retainer clean                                                        # Clean all retained messages
retainer clean <Topic>                                                # Clean retained messages by the specified topic filter
--------------------------------------------------------------------------------------------------------------
telemetry enable                                                      # Enable telemetry
telemetry disable                                                     # Disable telemetry
telemetry get data                                                    # Get reported telemetry data
--------------------------------------------------------------------------------------------------------------
rules list                                                            # List all rules
rules show <RuleId>                                                   # Show a rule
rules create                                                          # Create a rule
rules delete <RuleId>                                                 # Delete a rule
--------------------------------------------------------------------------------------------------------------
rule-actions list                                                     # List actions
rule-actions show <ActionId>                                          # Show a rule action
--------------------------------------------------------------------------------------------------------------
resources create                                                      # Create a resource
resources list [-t <ResourceType>]                                    # List resources
resources show <ResourceId>                                           # Show a resource
resources delete <ResourceId>                                         # Delete a resource
resources update <ResourceId> [-c <config>] [-d <description>]        # Update a resource
--------------------------------------------------------------------------------------------------------------
resource-types list                                                   # List all resource-types
resource-types show <Type>                                            # Show a resource-type
--------------------------------------------------------------------------------------------------------------
modules list                                                          # Show loaded modules
modules load <Module>                                                 # Load module
modules unload <Module>                                               # Unload module
modules reload <Module>                                               # Reload module
bash-5.0$ ./emqx_ctl pluginx list
Usage: emqx_ctl
--------------------------------------------------------------------------------------------------------------

本文发布于:2024-02-02 07:39:30,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170683077142337.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:双向   使用手册   代码   emq   ssl
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23