first commit

master
hwf452 3 years ago
parent 68560b54f6
commit 16488f3c23

Binary file not shown.

@ -0,0 +1,274 @@
# Created by .ignore support plugin (hsz.mobi)
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/dictionaries
.idea/**/shelf
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
cmake-build-release/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
### Java template
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### Eclipse template
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
/.idea/
/eureka-server/.mvn/
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/dictionaries
.idea/**/shelf
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
cmake-build-release/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
### Java template
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### Eclipse template
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
*.cmd
*.iml
*.mvn
*/mvnw
*/target
/logs/

@ -0,0 +1,29 @@
# SpringCloud-Example
本项目包含了 Spring Cloud 系列组件的使用 Demo 集合,及在此 Demo 基础上的添加分布式应用系列实践:
[系列文章地址](http://www.gxitsky.com/categories/Spring-Cloud系列/)http://www.gxitsky.com/categories/Spring-Cloud系列/
Bloghttp://www.gxitsky.com/
Githubhttps://github.com/gxing19/SpringCloud-Example
Giteehttps://gitee.com/gxing19/SpringCloud-Example
## Spring Cloud 系列组件 Demo
1. Eureka 注册中心配置、集群、监控
2. Ribbon 客户端负载均衡
3. Feign 声明式 REST 客户端
4. Hystrix 服务容错断路器
5. Zuul AIP网关路由和过滤器
6. Config Server JDBC 实现
7. Config Server Git 实现
8. Sleuth 分布式链路跟踪
9. Spring Cloud Bus 消息总线
10. Spring Cloud Stream 消息驱动
## 分布式应用系列
1. 微服务之间调用的安全认证-基本 JWT 实现,使用 java-jwt 库
## 更新日志
1. 同步到 Gitee(2020-08-01)

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

@ -0,0 +1,142 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.rehome</groupId>
<artifactId>admin-client-appmqttserver-yf</artifactId>
<version>1.0.0</version>
<name>admin-client-appmqttserver-yf</name>
<description>admin-client-appmqttserver-yf</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2020.0.3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.1.0</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,73 @@
package com.rehome.adminclientappmqttserveryf;
import com.rehome.adminclientappmqttserveryf.controller.UseryfController;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.google.gson.Gson;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.util.Map;
@SpringBootApplication
@EnableEurekaClient
@EnableJpaAuditing
@EnableScheduling
public class AdminClientAppmqttserverYfApplication implements CommandLineRunner, ApplicationContextAware {
/**
* Spring
*/
private ApplicationContext applicationContext;
/**
*/
@Resource
private UseryfController userYfController;
public static void main(String[] args) {
SpringApplication.run(AdminClientAppmqttserverYfApplication.class, args);
}
/**
* applicationContext(main使,mainstatic,)
* @param args
*/
@Override
public void run(String... args) throws Exception {
//在这里可以调用applicationContext了
Map<String, Object> controllers = applicationContext.getBeansWithAnnotation(RequestMapping.class);
Gson gson = new Gson();
// for (Map.Entry<String, Object> entry : controllers.entrySet()) {
// System.out.println("------------------------");
// System.out.println(entry.getKey());//demo1Controller
// }
try {
if (userYfController != null) {
System.out.println("------------------------");
System.out.println("UseryfController is not empty");
MqttRSAClientYFAPP client_yf = new MqttRSAClientYFAPP();
client_yf.start(userYfController);
} else {
System.out.println("UseryfController is empty");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}

@ -0,0 +1,124 @@
package com.rehome.adminclientappmqttserveryf;
import com.google.gson.Gson;
import com.rehome.adminclientappmqttserveryf.controller.UseryfController;
import com.rehome.adminclientappmqttserveryf.entity.Useryf;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttRSAClientYFAPP {
/**
* ip
*/
public static final String MQTT_BROKER_HOST = "tcp://39.101.173.20:1883";
/**
*
*/
public static final String MQTT_CLIENT_ID = "AppServer_YF_APP_server_01";
/**
*
*/
public static final String USERNAME = "admin";
/**
*
*/
public static final String PASSWORD = "public";
/**
*
*/
public static final String TOPIC_FILTER = "app_push_yf";
private volatile static MqttClient mqttClient;
private static MqttConnectOptions options;
private static int qos = 2;
private UseryfController userController;
public MqttRSAClientYFAPP(){
try {
// host为主机名clientid即连接MQTT的客户端ID一般以客户端唯一标识符表示
// MemoryPersistence设置clientid的保存形式默认为以内存保存
mqttClient = new MqttClient(MQTT_BROKER_HOST, MQTT_CLIENT_ID, new MemoryPersistence());
// 配置参数信息
options = new MqttConnectOptions();
// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录
// 这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession(true);
// 设置用户名
options.setUserName(USERNAME);
// 设置密码
options.setPassword(PASSWORD.toCharArray());
// 设置超时时间 单位为秒
options.setConnectionTimeout(10);
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线但这个方法并没有重连的机制
options.setKeepAliveInterval(20);
//断线重连
options.setAutomaticReconnect(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public void start(UseryfController userController) {
this.userController=userController;
try {
// 连接
mqttClient.connect(options);
// 订阅
mqttClient.subscribe(TOPIC_FILTER,qos);
// 设置回调
mqttClient.setCallback(new MqttCallbackExtended(){
@Override
public void connectionLost(Throwable throwable) {
System.out.println("connectionLost");
try {
mqttClient.reconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
System.out.println("topic:"+s);
System.out.println("Qos:"+mqttMessage.getQos());
System.out.println("message RSA:"+new String(mqttMessage.getPayload()));
try {
String messageDe = RSAAndroid.decryptByPrivateKeyForSpiltStr(new String(mqttMessage.getPayload()), RSAAndroid.privateRsaKey);
System.out.println("message content:"+messageDe);
Gson gson = new Gson();
Useryf userInfo = gson.fromJson(messageDe, Useryf.class);
System.out.println(userInfo.getUsername());
System.out.println(userInfo.getPassword());
System.out.println(userInfo.getDate());
System.out.println(userInfo.getNfc());
userController.saveUserYF(userInfo);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("deliveryComplete---------"+ iMqttDeliveryToken.isComplete());
}
@Override
public void connectComplete(boolean b, String s) {
//连接成功后调用
try {
mqttClient.subscribe(TOPIC_FILTER,qos);//具体订阅代码
} catch (MqttException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,526 @@
package com.rehome.adminclientappmqttserveryf;
/**
* @ Author : huangwenfei
* @ Date : Created in 2021/8/11 10:44
* @ Version : $1.0.0.0
* @ Description:
*/
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
public class RSAAndroid {
private static String TAG = "RSAAndroid";
public static final String RSA = "RSA";// 非对称加密密钥算法
//public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";//加密填充方式
public static final String ECB_PKCS1_PADDING = "RSA";//加密填充方式 RSA/None/PKCS1Padding
public static final int DEFAULT_KEY_SIZE = 2048;//秘钥默认长度
public static final byte[] DEFAULT_SPLIT = "#PART#".getBytes(); // 当要加密的内容超过bufferSize则采用partSplit进行分块加密
public static final int DEFAULT_BUFFERSIZE = (DEFAULT_KEY_SIZE / 8) - 11;// 当前秘钥支持加密的最大字节数
public static String publicRsaKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmMLyJw1CAl25lnDgEeYZvOps+1pSi93Q39djEniGNo5uUKVEkqDIayTli2zreX10HqT2jTtDN9APtwuEhWazP/VgOXoWsztbtZtSwJGM6Eg0R9zDCbKyQt5Qhg3jkTrXrvrGn7j/ZP56VNWELv/i5dsRCTccr1MeIyxjOC2pojCOsrTN4HZzgBj+GEUKPRLcKOiPfOsoP7HgkAua82vTOIgWpqIp+1PIfcjjCqzOsSv5PQnGP75+flIXtz75OKo/9hX9zl5JHNcH3SC6nS8Czii9E292XIsBtKdQijvNMn+YcmKFo6mZOUXHdO506NoKkxRny5fbKiPf/oqTA7Zx5QIDAQAB";
public static String privateRsaKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCYwvInDUICXbmWcOAR5hm86mz7WlKL3dDf12MSeIY2jm5QpUSSoMhrJOWLbOt5fXQepPaNO0M30A+3C4SFZrM/9WA5ehazO1u1m1LAkYzoSDRH3MMJsrJC3lCGDeOROteu+safuP9k/npU1YQu/+Ll2xEJNxyvUx4jLGM4LamiMI6ytM3gdnOAGP4YRQo9Etwo6I986yg/seCQC5rza9M4iBamoin7U8h9yOMKrM6xK/k9CcY/vn5+Uhe3Pvk4qj/2Ff3OXkkc1wfdILqdLwLOKL0Tb3ZciwG0p1CKO80yf5hyYoWjqZk5Rcd07nTo2gqTFGfLl9sqI9/+ipMDtnHlAgMBAAECggEATJd5yCC6lusdMRO5FOBUyUaUi9X2i1AU+RZKAynQySvSnbavUgExW58tRCHBUrGW9gJp59ft1N8J8hHhSO18NDY4H7laBlVdnwmYjRqtFo2VQO6sD4G8JRDION5f2iIxn/b2fYDI9H8vILfJRbNgtTSILyGlzTYUZzhLKxCh+8IsN96Nic8wa5COd1vZZmdhf2y8TG8clFWmozaScNSAATx7y+8XLVWjjWiIRZ6xQvx0uQPUParc9KihXXTKR2pA22yPIdz+U4MGD4kC0eczlcFKZ/dYv9e7OIGgnJfT0idSCu7nYb1pxJ1LxD9fS6IScNTF5dSe0OIL98e+XdyoAQKBgQDRep+5cW4iAKrEMH+djmcXAkoMiYtNVtnu0efLE8dP6vjYytQi368X9SdcASbfrQ31eEZmr/xQnlUF8oyHGkI38YS8dpAHzQcrkP3BljbbzB/3gJZaUdghGsDrK0xAJIzzmFKQpeKnGtr23vxUgaGrNsCYvQ0eQ7+5056KXS4r5QKBgQC6r8xtRSaje6L4WIydjWvYywsmRO0Of0aJLMDA/Wt2MWhHfh7ba9oI1cKGN80ap7xB2a9lQLgpv+C53wNtE5SpvjxsikAj96nUMMhGy9ojXrUith6HQhiINETz6Shnznd+AyrXP6KI/RpfA5nkDB5nrJxODwtYLP467IL7Cv7OAQKBgQCl4KxKdH/5fP28jYsAgJsxpSZt9xzQCU5Zxu396ZOSvUaApVyGoQpNtluMh3z48lhzYOKevgzW6gn5w69z7F8zXZT2iAxVoQ1kelP2z7RxKJrHqpNkwhqbXEwX7RlcUZUr8BqxYCqymJl7k+fMIzqaEalBSbLxnEReKi0I8/Bz4QKBgHK4b0ZCtVDHPEmimJ6E9l4dv/c/afF7swu+zaCK2ouiJvOwBCRQbYb6XPR/u/GCXASXUdpF4CX/vIhcDE3uN2/r8FO+zVWM7vbvF1OyF5WesG7pPW9e5ZZlkG3WvLa1wOZV6fCmMSo/ZwI2Q05JSDHrd43cXttLotrw1jiQ9C4BAoGBAKi4SOoOVQ5J5HQCDkBwPbG1AOLHFinzfoDl26GF/8Hy7fmmd1JiRTFldQp/A9VTAABz3sVYmMB92HSIaJhuDMoYJNI2Cf/cZifsv7vUL8cbLn+lPsKsebiuB0m0g4P2qLwLfegfNGEgA7lA5HIz3SELqbdp3iuqJeQl1fsJqD74";
public static byte[] decryptBASE64(String key) throws Exception {
return Base64.decodeBase64(key);
}
public static String encryptBASE64(byte[] key) throws Exception {
return Base64.encodeBase64String(key);
}
/**
* RSA
*
* @param keyLength 5122048
* 1024
* @return
*/
public static KeyPair generateRSAKeyPair(int keyLength) {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
*
*
* @param data
*/
public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
// 得到公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey keyPublic = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
// 加密数据
Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
cp.init(Cipher.ENCRYPT_MODE, keyPublic);
return cp.doFinal(data);
}
/**
*
*
* @param data
* @param privateKey
* @return byte[]
*/
public static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception {
// 得到私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey keyPrivate = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
// 数据加密
Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
cipher.init(Cipher.ENCRYPT_MODE, keyPrivate);
return cipher.doFinal(data);
}
/**
*
*
* @param data
* @param publicKey
* @return byte[]
*/
public static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
// 得到公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey keyPublic = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
// 数据解密
Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
cipher.init(Cipher.DECRYPT_MODE, keyPublic);
return cipher.doFinal(data);
}
/**
* 使
*/
public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {
// 得到私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey keyPrivate = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
// 解密数据
Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
cp.init(Cipher.DECRYPT_MODE, keyPrivate);
byte[] arr = cp.doFinal(encrypted);
return arr;
}
/**
*
*/
public static byte[] encryptByPublicKeyForSpilt(byte[] data, byte[] publicKey) throws Exception {
int dataLen = data.length;
if (dataLen <= DEFAULT_BUFFERSIZE) {
return encryptByPublicKey(data, publicKey);
}
List<Byte> allBytes = new ArrayList<Byte>(2048);
int bufIndex = 0;
int subDataLoop = 0;
byte[] buf = new byte[DEFAULT_BUFFERSIZE];
for (int i = 0; i < dataLen; i++) {
buf[bufIndex] = data[i];
if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
subDataLoop++;
if (subDataLoop != 1) {
for (byte b : DEFAULT_SPLIT) {
allBytes.add(b);
}
}
byte[] encryptBytes = encryptByPublicKey(buf, publicKey);
for (byte b : encryptBytes) {
allBytes.add(b);
}
bufIndex = 0;
if (i == dataLen - 1) {
buf = null;
} else {
buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
}
}
}
byte[] bytes = new byte[allBytes.size()];
{
int i = 0;
for (Byte b : allBytes) {
bytes[i++] = b.byteValue();
}
}
return bytes;
}
/**
* 使
*
* @param data
* @param privateKey
*/
public static byte[] encryptByPrivateKeyForSpilt(byte[] data, byte[] privateKey) throws Exception {
int dataLen = data.length;
if (dataLen <= DEFAULT_BUFFERSIZE) {
return encryptByPrivateKey(data, privateKey);
}
List<Byte> allBytes = new ArrayList<Byte>(2048);
int bufIndex = 0;
int subDataLoop = 0;
byte[] buf = new byte[DEFAULT_BUFFERSIZE];
for (int i = 0; i < dataLen; i++) {
buf[bufIndex] = data[i];
if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
subDataLoop++;
if (subDataLoop != 1) {
for (byte b : DEFAULT_SPLIT) {
allBytes.add(b);
}
}
byte[] encryptBytes = encryptByPrivateKey(buf, privateKey);
for (byte b : encryptBytes) {
allBytes.add(b);
}
bufIndex = 0;
if (i == dataLen - 1) {
buf = null;
} else {
buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
}
}
}
byte[] bytes = new byte[allBytes.size()];
{
int i = 0;
for (Byte b : allBytes) {
bytes[i++] = b.byteValue();
}
}
return bytes;
}
/**
*
*
* @param encrypted
* @param publicKey
*/
public static byte[] decryptByPublicKeyForSpilt(byte[] encrypted, byte[] publicKey) throws Exception {
int splitLen = DEFAULT_SPLIT.length;
if (splitLen <= 0) {
return decryptByPublicKey(encrypted, publicKey);
}
int dataLen = encrypted.length;
List<Byte> allBytes = new ArrayList<Byte>(1024);
int latestStartIndex = 0;
for (int i = 0; i < dataLen; i++) {
byte bt = encrypted[i];
boolean isMatchSplit = false;
if (i == dataLen - 1) {
// 到data的最后了
byte[] part = new byte[dataLen - latestStartIndex];
System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
byte[] decryptPart = decryptByPublicKey(part, publicKey);
for (byte b : decryptPart) {
allBytes.add(b);
}
latestStartIndex = i + splitLen;
i = latestStartIndex - 1;
} else if (bt == DEFAULT_SPLIT[0]) {
// 这个是以split[0]开头
if (splitLen > 1) {
if (i + splitLen < dataLen) {
// 没有超出data的范围
for (int j = 1; j < splitLen; j++) {
if (DEFAULT_SPLIT[j] != encrypted[i + j]) {
break;
}
if (j == splitLen - 1) {
// 验证到split的最后一位都没有break则表明已经确认是split段
isMatchSplit = true;
}
}
}
} else {
// split只有一位则已经匹配了
isMatchSplit = true;
}
}
if (isMatchSplit) {
byte[] part = new byte[i - latestStartIndex];
System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
byte[] decryptPart = decryptByPublicKey(part, publicKey);
for (byte b : decryptPart) {
allBytes.add(b);
}
latestStartIndex = i + splitLen;
i = latestStartIndex - 1;
}
}
byte[] bytes = new byte[allBytes.size()];
{
int i = 0;
for (Byte b : allBytes) {
bytes[i++] = b.byteValue();
}
}
return bytes;
}
/**
* 使
*/
public static byte[] decryptByPrivateKeyForSpilt(byte[] encrypted, byte[] privateKey) throws Exception {
int splitLen = DEFAULT_SPLIT.length;
if (splitLen <= 0) {
return decryptByPrivateKey(encrypted, privateKey);
}
int dataLen = encrypted.length;
List<Byte> allBytes = new ArrayList<Byte>(1024);
int latestStartIndex = 0;
for (int i = 0; i < dataLen; i++) {
byte bt = encrypted[i];
boolean isMatchSplit = false;
if (i == dataLen - 1) {
// 到data的最后了
byte[] part = new byte[dataLen - latestStartIndex];
System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
byte[] decryptPart = decryptByPrivateKey(part, privateKey);
for (byte b : decryptPart) {
allBytes.add(b);
}
latestStartIndex = i + splitLen;
i = latestStartIndex - 1;
} else if (bt == DEFAULT_SPLIT[0]) {
// 这个是以split[0]开头
if (splitLen > 1) {
if (i + splitLen < dataLen) {
// 没有超出data的范围
for (int j = 1; j < splitLen; j++) {
if (DEFAULT_SPLIT[j] != encrypted[i + j]) {
break;
}
if (j == splitLen - 1) {
// 验证到split的最后一位都没有break则表明已经确认是split段
isMatchSplit = true;
}
}
}
} else {
// split只有一位则已经匹配了
isMatchSplit = true;
}
}
if (isMatchSplit) {
byte[] part = new byte[i - latestStartIndex];
System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
byte[] decryptPart = decryptByPrivateKey(part, privateKey);
for (byte b : decryptPart) {
allBytes.add(b);
}
latestStartIndex = i + splitLen;
i = latestStartIndex - 1;
}
}
byte[] bytes = new byte[allBytes.size()];
{
int i = 0;
for (Byte b : allBytes) {
bytes[i++] = b.byteValue();
}
}
return bytes;
}
/**
*
*/
public static String encryptByPublicKeyForSpiltStr(String data, String publicKey) throws Exception {
byte[] encryptBytes = encryptByPublicKeyForSpilt(data.getBytes(StandardCharsets.UTF_8), publicKey.getBytes());
return encryptBASE64(encryptBytes);
}
/**
* 使
*
* @param data
* @param privateKey
*/
public static String encryptByPrivateKeyForSpiltStr(String data, String privateKey) throws Exception {
byte[] encryptBytes = encryptByPrivateKeyForSpilt(data.getBytes(StandardCharsets.UTF_8), privateKey.getBytes());
return encryptBASE64(encryptBytes);
}
/**
*
*
* @param encrypted
* @param publicKey
*/
public static String decryptByPublicKeyForSpiltStr(String encrypted, String publicKey) throws Exception {
byte[] decryptBytes = decryptByPublicKeyForSpilt(decryptBASE64(encrypted), publicKey.getBytes());
return new String(decryptBytes,StandardCharsets.UTF_8);
}
/**
* 使
*/
public static String decryptByPrivateKeyForSpiltStr(String encrypted, String privateKey) throws Exception {
byte[] decryptBytes = decryptByPrivateKeyForSpilt(decryptBASE64(encrypted), privateKey.getBytes());
return new String(decryptBytes,StandardCharsets.UTF_8);
}
public static void testEncrypt1(String content) {
//生成秘钥对
KeyPair keyPair = RSAAndroid.generateRSAKeyPair(RSAAndroid.DEFAULT_KEY_SIZE);
//公钥
PublicKey publicKey = keyPair.getPublic();
//私钥
PrivateKey privateKey = keyPair.getPrivate();
long start;
long end;
byte[] encryptBytes = new byte[0];
byte[] decryptBytes = new byte[0];
String encryStr, decryStr;
try {
System.out.println("公钥:" + encryptBASE64(RSAAndroid.publicRsaKey.getBytes()));
//公钥加密
start = System.currentTimeMillis();
encryptBytes = RSAAndroid.encryptByPublicKeyForSpilt(content.getBytes(StandardCharsets.UTF_8), RSAAndroid.publicRsaKey.getBytes());
System.out.println("testEncrypt: 公钥加密 encryptBytes:" + encryptBytes);
end = System.currentTimeMillis();
System.out.println("公钥加密耗时 cost time---->" + (end - start));
//encryStr = BASE64Encoder.encode(encryptBytes);
encryStr = encryptBASE64(encryptBytes);
// Log.e(TAG, "加密后json数据 --1-->" + encryStr);
System.out.println("加密后json数据长度 --1-->" + encryStr.length());
System.out.println("testEncrypt: encryStr:" + encryStr);
//私钥解密
System.out.println("私钥:" + encryptBASE64(RSAAndroid.privateRsaKey.getBytes()));
start = System.currentTimeMillis();
decryptBytes = RSAAndroid.decryptByPrivateKeyForSpilt(decryptBASE64(encryStr), RSAAndroid.privateRsaKey.getBytes());
decryStr = new String(decryptBytes);
System.out.println("testEncrypt: 私钥解密 decryStr:" + decryStr);
end = System.currentTimeMillis();
System.out.println("私钥解密耗时 cost time---->" + (end - start));
System.out.println("解密后json数据 --1-->" + decryStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testEncrypt2(String content) {
//生成秘钥对
KeyPair keyPair = RSAAndroid.generateRSAKeyPair(RSAAndroid.DEFAULT_KEY_SIZE);
//公钥
PublicKey publicKey = keyPair.getPublic();
//私钥
PrivateKey privateKey = keyPair.getPrivate();
long start;
long end;
byte[] encryptBytes = new byte[0];
byte[] decryptBytes = new byte[0];
String encryStr, decryStr;
try {
//私钥加密
start = System.currentTimeMillis();
encryptBytes = RSAAndroid.encryptByPrivateKeyForSpilt(content.getBytes(StandardCharsets.UTF_8), RSAAndroid.privateRsaKey.getBytes());
end = System.currentTimeMillis();
System.out.println("私钥加密密耗时 cost time---->" + (end - start));
encryStr = encryptBASE64(encryptBytes);
// Log.e(TAG, "加密后json数据 --2-->" + encryStr);
System.out.println("加密后json数据长度 --2-->" + encryStr.length());
System.out.println("testEncrypt: 私钥加密密 encryStr:" + encryStr);
//公钥解密
start = System.currentTimeMillis();
decryptBytes = RSAAndroid.decryptByPublicKeyForSpilt(decryptBASE64(encryStr), RSAAndroid.publicRsaKey.getBytes());
decryStr = new String(decryptBytes);
System.out.println("testEncrypt: 公钥解密 decryStr:" + decryStr);
end = System.currentTimeMillis();
System.out.println("公钥解密耗时 cost time---->" + (end - start));
System.out.println("解密后json数据 --2-->" + decryStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testEncrypt3(String content) {
long start;
long end;
String encryStr, decryStr;
try {
//公钥加密
System.out.println("公钥:" + RSAAndroid.publicRsaKey);
start = System.currentTimeMillis();
encryStr = RSAAndroid.encryptByPublicKeyForSpiltStr(content, RSAAndroid.publicRsaKey);
end = System.currentTimeMillis();
System.out.println("公钥加密耗时 cost time---->" + (end - start));
System.out.println("加密后json数据长度 --1-->" + encryStr.length());
System.out.println("testEncrypt: 公钥加密 encryStr:" + encryStr);
//私钥解密
System.out.println("私钥:" + RSAAndroid.privateRsaKey);
start = System.currentTimeMillis();
encryStr = "X6Ad0LpiBP7ze/cEgwGkYS53zG5ozY1Nrk2HzrrGlWqFZdyrmYihc1Fo3pjxxfOJi60zkZXguPt197vdtf2NHjtBCamvGt8DYhvfGUFP0YSod11GckQQaUslUkwPjQKTGJ46Kdy7Y2gMKK7EdEabEmTPl/XIT9fDFX/nMWgAutcQ15Gq5FRwWQH7sSVNF5bjrxxBs7Q/JwsCsU+xl0LraifUf+1O6NzCHc4ll7dmWq6EGORjaSVYka8ItuI4hhVWffcrOhY1vDqjFkY+Mzac9ppgk1nc5StMMNGyPC4OYsLkqZa5h8acK8YhSi7dpj58Lo/yJWqMmewiGDSskrcFXCNQQVJUI10H9WmD3b//98jW6cq3awLqmpoZmjuN3fm8vx1KPOCEZs2GlM7/wCEUMabV7O5EsTtRf+6pqHYTPzZfxt2lXEEJviktjguG1WI71nwg+1XyIx5tn818XiYvs0L02hi3sWpQkk/NJ4QaE3LziuCMrgDU/GcFzYLybU627yAPPPLjB9wVZGefwUdWjMtY5AzPMBa9eNjsMaHAGe2zbnopafuouwsjH+uEZd2rzT3Uacb7+pNjl94XiB/0Xhwl1n5bi6HbT3aY2jC6YbKqCp5XQaLCbuefaRVCLC6pOHmNX6NKni98/bYKQ6XfhDoA56gJAEVsAaj/a6vpzVIMsej5zDI=";
decryStr = RSAAndroid.decryptByPrivateKeyForSpiltStr(encryStr, RSAAndroid.privateRsaKey);
end = System.currentTimeMillis();
System.out.println("私钥解密耗时 cost time---->" + (end - start));
System.out.println("解密后json数据长度 --1-->" + decryStr.length());
System.out.println("testEncrypt: 私钥解密 decryStr:" + decryStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testEncrypt4(String content) {
long start;
long end;
String encryStr, decryStr;
try {
System.out.println("公钥:" + RSAAndroid.publicRsaKey);
//私钥加密
start = System.currentTimeMillis();
encryStr = RSAAndroid.encryptByPrivateKeyForSpiltStr(content, RSAAndroid.privateRsaKey);
end = System.currentTimeMillis();
System.out.println("私钥加密密耗时 cost time---->" + (end - start));
System.out.println("加密后json数据长度 --2-->" + encryStr.length());
System.out.println("testEncrypt: 私钥加密 encryStr:" + encryStr);
//公钥解密
System.out.println("私钥:" + RSAAndroid.privateRsaKey);
start = System.currentTimeMillis();
decryStr = RSAAndroid.decryptByPublicKeyForSpiltStr(encryStr, RSAAndroid.publicRsaKey);
end = System.currentTimeMillis();
System.out.println("公钥解密耗时 cost time---->" + (end - start));
System.out.println("解密后json数据 --2-->" + decryStr);
System.out.println("testEncrypt: 公钥解密 decryStr:" + decryStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
RSAAndroid.testEncrypt3("8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。");
}
}

@ -0,0 +1,66 @@
package com.rehome.adminclientappmqttserveryf;
import java.io.Serializable;
public class UserInfo implements Serializable {
private String date;
public String getImeinum() {
return imeinum;
}
public void setImeinum(String imeinum) {
this.imeinum = imeinum;
}
private String imeinum;
private String sysversion;
private String username;
private String password;
private String phonemodel;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhonemodel() {
return phonemodel;
}
public void setPhonemodel(String phonemodel) {
this.phonemodel = phonemodel;
}
public String getSysversion() {
return sysversion;
}
public void setSysversion(String sysversion) {
this.sysversion = sysversion;
}
}

@ -0,0 +1,20 @@
package com.rehome.adminclientappmqttserveryf.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @name: SecuritySecureConfig
* @desc:
* @author: gxing
* @date: 2019-06-04 18:15
**/
@Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/actuator/**");
}
}

@ -0,0 +1,40 @@
package com.rehome.adminclientappmqttserveryf.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @ Author : huangwenfei
* @ Date : Created in 2021/5/17 9:15
* @ Version : $1.0.0.0
* @ Description: Swagger3 UI
*/
@Configuration
public class Swagger3Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger3接口文档")
.description("更多请咨询服务开发者hwf452")
.contact(new Contact("hwf452", "http://www.baidu.com", "hwf452@163.com"))
.version("1.0")
.build();
}
}

@ -0,0 +1,29 @@
package com.rehome.adminclientappmqttserveryf.controller;
import com.rehome.adminclientappmqttserveryf.entity.Useryf;
import com.rehome.adminclientappmqttserveryf.service.UseryfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
*
* </p>
*
* @author huangwenfei
* @since 2022-03-09
*/
@RestController
@RequestMapping("/useryf")
public class UseryfController {
@Autowired
private UseryfService userYfService;
public void saveUserYF(Useryf user){
userYfService.saveByUsernameYF(user);
}
}

@ -0,0 +1,14 @@
package com.rehome.adminclientappmqttserveryf.dao;
import com.rehome.adminclientappmqttserveryf.entity.Useryf;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* T :
* ID :OID
*
*/
public interface UseryRepository extends JpaRepository<Useryf,String> {
//方法名称必须要遵循驼峰式命名规则findBy关键字+属性名称(首字母大写)+查询条件(首字母大写)
Useryf findByUsername(String username);
}

@ -0,0 +1,33 @@
package com.rehome.adminclientappmqttserveryf.entity;
import java.io.Serializable;
import lombok.Data;
import org.hibernate.annotations.Proxy;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
/**
* @author huangwenfei
* @since 2022-03-09
*/
@EntityListeners(AuditingEntityListener.class)
@Proxy(lazy = false)
@Data
@Entity
public class Useryf implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String username;
private String password;
private String nfc;
@Column( length = 32)
private String date;
}

@ -0,0 +1,15 @@
package com.rehome.adminclientappmqttserveryf.service;
import com.rehome.adminclientappmqttserveryf.entity.Useryf;
/**
* <p>
*
* </p>
*
* @author huangwenfei
* @since 2022-03-09
*/
public interface UseryfService {
public void saveByUsernameYF(Useryf user);
}

@ -0,0 +1,38 @@
package com.rehome.adminclientappmqttserveryf.service.impl;
import com.rehome.adminclientappmqttserveryf.dao.UseryRepository;
import com.rehome.adminclientappmqttserveryf.entity.Useryf;
import com.rehome.adminclientappmqttserveryf.service.UseryfService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
/**
* <p>
*
* </p>
*
* @author huangwenfei
* @since 2022-03-09
*/
@Service
@Transactional
public class UseryfServiceImpl implements UseryfService {
@Resource
private UseryRepository useryRepository;
@Override
public void saveByUsernameYF(Useryf user) {
// Useryf useryfDb = this.useryRepository.findByUsername(user.getUsername());
// if (useryfDb != null) {
// useryfDb.setDate(user.getDate());
// useryfDb.setPassword(user.getPassword());
// useryfDb.setNfc(user.getNfc());
// this.useryRepository.save(useryfDb);
// } else {
// this.useryRepository.save(user);
// }
this.useryRepository.save(user);
}
}

@ -0,0 +1,91 @@
package com.rehome.adminclientappmqttserveryf.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-27 9:35
* @description: http
*/
public class HttpURLConnectionUtil {
/**
* @date 2021-04-29 11:23
* @description: get
* @Param: urlStr geturl
*/
public static String getNetData(String urlStr) {
HttpURLConnection conn = null;
//连接成功后我们是要读取数据的 所以要有一个输入流
InputStream inputStream = null;
// 因为读取的都是文本信息 所以使用BufferedReader
BufferedReader bufferedReader = null;
//StringBuilder来把接收到的数据拼接起来
StringBuilder result = new StringBuilder();
try {
// 读取初始url 并且创建对象
URL url = new URL(urlStr);
//打开url连接
conn = (HttpURLConnection) url.openConnection();
//设置连接
//请求的方法
conn.setRequestMethod("GET");
//设置主机连接超时(单位:毫秒)
// 发送请求端 连接到 url目标地址端的时间 受距离长短和网络速度的影响
conn.setConnectTimeout(15000);
//设置从主机读取数据超时(单位:毫秒)
// 连接成功后 获取数据的时间 受数据量和服务器处理数据的影响
conn.setReadTimeout(60000);
//设置请求参数 可以指定接收json参数 服务端的key为content-type
conn.setRequestProperty("Accept", "application/json");
//发送请求
conn.connect();
//获取响应码 如果响应码不为200 表示请求不成功
if (conn.getResponseCode() != 200) {
//todo 此处应该增加异常处理手段
return "请求失败!!!";
}
//获取响应码 如果响应码为200 表示请求成功 然后可以读取数据
//获取输入流 然后读取数据
inputStream = conn.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
//逐行读取数据
String line;//用来读取数据
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
//System.out.print(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭各种流
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
}

@ -0,0 +1,68 @@
package com.rehome.adminclientappmqttserveryf.utils;
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-26 9:35
* @description: http
*/
public class WeatherUtil {
/**
* @date 2021-04-29 11:23
* @description: get
* @Param: url geturl
*/
public static String analysisUrl(String url){
HttpURLConnection httpConnection = null;
String output = "";
try {
URL targetUrl = new URL(url);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Content-Type",
"application/json");
InputStreamReader isr = new InputStreamReader(httpConnection
.getInputStream(),"utf-8");
BufferedReader responseBuffer = new BufferedReader(isr);
output = responseBuffer.readLine();
} catch (Exception e) {
} finally {
httpConnection.disconnect();
}
return output;
}
/**
* @date 2021-04-29 11:23
* @description: get
* @Param: url geturl
*/
public static String analysisUrlGzip(String url){
HttpURLConnection httpConnection = null;
String output = "";
try {
URL targetUrl = new URL(url);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Content-Type", "application/json");
InputStream stream = new GZIPInputStream(httpConnection.getInputStream());
output = IOUtils.toString(stream,"utf-8");
} catch (Exception e) {
} finally {
httpConnection.disconnect();
}
return output;
}
}

@ -0,0 +1,67 @@
server:
port: 8873
management:
endpoint:
health:
show-details: always
endpoints:
web:
exposure:
include: '*'
eureka:
instance:
prefer-ip-address: true
lease-renewal-interval-in-seconds: 10
health-check-url-path: /actuator/health
metadata-map:
startup: ${random.int}
user:
name: ${spring.security.user.name}
password: ${spring.security.user.password}
client:
registry-fetch-interval-seconds: 5
serviceUrl:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@eureka.master.com:8761/eureka,http://${spring.security.user.name}:${spring.security.user.password}@eureka.slave.com:8762/eureka
spring:
application:
name: admin-client-appmqttserver
security:
user:
name: admin
password: Admin123456
boot:
admin:
client:
instance:
metadata:
user:
name: ${spring.security.user.name}
password: ${spring.security.user.password}
username: user
password: 123456
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver #com.mysql.jdbc.Driver # 8.0 com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/appserver?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
username: root
password: Skyinno251,
jpa:
database: mysql # 配置 DBMS 类型
show-sql: true # 配置是否将执行的 SQL 输出到日志
open-in-view: true
hibernate:
ddl-auto: update # 第一次建表create 后面用update要不然每次重启都会新建表
servlet:
multipart:
# 开启 multipart 上传功能
enabled: true
# 文件写入磁盘的阈值
file-size-threshold: 2KB
# 最大文件大小
max-file-size: 200MB
# 最大请求大小
max-request-size: 215MB
logging:
level:
root: info
com.example: debug

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--日志文件主目录:这里${user.home}为当前服务器用户主目录-->
<property name="LOG_HOME" value="${user.home}/admin-client-appmqttserver-yf_log"/>
<!--日志文件主目录:这里${user.home}为当前服务器用户主目录-->
<property name="APP_NAME" value="admin-client-appmqttserver-yf"/>
<!--输出日志到 命令行-->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!--输出日志到 日志文件-->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--设置策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件路径:这里%d{yyyyMMdd}表示按天分类日志-->
<FileNamePattern>${LOG_HOME}/%d{yyyyMMdd}/${APP_NAME}.log</FileNamePattern>
<!--日志保留天数-->
<MaxHistory>15</MaxHistory>
</rollingPolicy>
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>50MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!--此处可以调整输出日志级别 改为debug可以看到更多日志包括hiber..、system debug类型以上的的日志-->
<root level="info">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>
</configuration>

@ -0,0 +1,13 @@
package com.rehome.adminclientappmqttserveryf;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AdminClientAppmqttserverYfApplicationTests {
@Test
void contextLoads() {
}
}

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

@ -0,0 +1,168 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.rehome</groupId>
<artifactId>admin-client-appmqttserver</artifactId>
<version>0.0.1</version>
<name>admin-client-appmqttserver</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2020.0.3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mybatis plus 代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<!--引入druid数据源-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,69 @@
package com.rehome.adminclientappmqttserver;
import com.rehome.adminclientappmqttserver.controller.UserController;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.google.gson.Gson;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
@SpringBootApplication
@EnableEurekaClient
@MapperScan("com.rehome.adminclientappmqttserver.dao")
public class AdminClientAppmqttserverApplication implements CommandLineRunner, ApplicationContextAware {
/**
* Spring
*/
private ApplicationContext applicationContext;
/**
*/
@Autowired
private UserController userController;
public static void main(String[] args) {
SpringApplication.run(AdminClientAppmqttserverApplication.class, args);
}
/**
* applicationContext(main使,mainstatic,)
* @param args
*/
@Override
public void run(String... args) throws Exception {
//在这里可以调用applicationContext了
Map<String, Object> controllers = applicationContext.getBeansWithAnnotation(RequestMapping.class);
Gson gson = new Gson();
// for (Map.Entry<String, Object> entry : controllers.entrySet()) {
// System.out.println("------------------------");
// System.out.println(entry.getKey());//demo1Controller
// }
try {
if (userController != null) {
System.out.println("------------------------");
System.out.println("UserController is not empty");
MqttRSAClient client = new MqttRSAClient();
client.start(userController);
} else {
System.out.println("UserController is empty");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}

@ -0,0 +1,131 @@
package com.rehome.adminclientappmqttserver;
import com.google.gson.Gson;
import com.rehome.adminclientappmqttserver.controller.UserController;
import com.rehome.adminclientappmqttserver.entity.User;
import com.rehome.adminclientappmqttserver.service.UserService;
import com.rehome.adminclientappmqttserver.service.impl.UserServiceImpl;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
public class MqttRSAClient {
/**
* ip
*/
public static final String MQTT_BROKER_HOST = "tcp://39.101.173.20:1883";
/**
*
*/
public static final String MQTT_CLIENT_ID = "AppServer_02";
/**
*
*/
public static final String USERNAME = "admin";
/**
*
*/
public static final String PASSWORD = "public";
/**
*
*/
public static final String TOPIC_FILTER = "app_push";
private volatile static MqttClient mqttClient;
private static MqttConnectOptions options;
private static int qos = 2;
private UserController userController;
public MqttRSAClient(){
try {
// host为主机名clientid即连接MQTT的客户端ID一般以客户端唯一标识符表示
// MemoryPersistence设置clientid的保存形式默认为以内存保存
mqttClient = new MqttClient(MQTT_BROKER_HOST, MQTT_CLIENT_ID, new MemoryPersistence());
// 配置参数信息
options = new MqttConnectOptions();
// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录
// 这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession(true);
// 设置用户名
options.setUserName(USERNAME);
// 设置密码
options.setPassword(PASSWORD.toCharArray());
// 设置超时时间 单位为秒
options.setConnectionTimeout(10);
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线但这个方法并没有重连的机制
options.setKeepAliveInterval(20);
//断线重连
options.setAutomaticReconnect(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public void start(UserController userController) {
this.userController=userController;
try {
// 连接
mqttClient.connect(options);
// 订阅
mqttClient.subscribe(TOPIC_FILTER,qos);
// 设置回调
mqttClient.setCallback(new MqttCallbackExtended(){
@Override
public void connectionLost(Throwable throwable) {
System.out.println("connectionLost");
try {
mqttClient.reconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
System.out.println("topic:"+s);
System.out.println("Qos:"+mqttMessage.getQos());
System.out.println("message RSA:"+new String(mqttMessage.getPayload()));
try {
String messageDe = RSAAndroid.decryptByPrivateKeyForSpiltStr(new String(mqttMessage.getPayload()), RSAAndroid.privateRsaKey);
System.out.println("message content:"+messageDe);
Gson gson = new Gson();
User userInfo = gson.fromJson(messageDe,User.class);
System.out.println(userInfo.getUsername());
System.out.println(userInfo.getPassword());
System.out.println(userInfo.getDate());
System.out.println(userInfo.getImeinum());
System.out.println(userInfo.getPhonemodel());
System.out.println(userInfo.getSysversion());
System.out.println(userInfo.getAppversion());
userController.saveUser(userInfo);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("deliveryComplete---------"+ iMqttDeliveryToken.isComplete());
}
@Override
public void connectComplete(boolean b, String s) {
//连接成功后调用
try {
mqttClient.subscribe(TOPIC_FILTER,qos);//具体订阅代码
} catch (MqttException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,526 @@
package com.rehome.adminclientappmqttserver;
/**
* @ Author : huangwenfei
* @ Date : Created in 2021/8/11 10:44
* @ Version : $1.0.0.0
* @ Description:
*/
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
public class RSAAndroid {
private static String TAG = "RSAAndroid";
public static final String RSA = "RSA";// 非对称加密密钥算法
//public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";//加密填充方式
public static final String ECB_PKCS1_PADDING = "RSA";//加密填充方式 RSA/None/PKCS1Padding
public static final int DEFAULT_KEY_SIZE = 2048;//秘钥默认长度
public static final byte[] DEFAULT_SPLIT = "#PART#".getBytes(); // 当要加密的内容超过bufferSize则采用partSplit进行分块加密
public static final int DEFAULT_BUFFERSIZE = (DEFAULT_KEY_SIZE / 8) - 11;// 当前秘钥支持加密的最大字节数
public static String publicRsaKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmMLyJw1CAl25lnDgEeYZvOps+1pSi93Q39djEniGNo5uUKVEkqDIayTli2zreX10HqT2jTtDN9APtwuEhWazP/VgOXoWsztbtZtSwJGM6Eg0R9zDCbKyQt5Qhg3jkTrXrvrGn7j/ZP56VNWELv/i5dsRCTccr1MeIyxjOC2pojCOsrTN4HZzgBj+GEUKPRLcKOiPfOsoP7HgkAua82vTOIgWpqIp+1PIfcjjCqzOsSv5PQnGP75+flIXtz75OKo/9hX9zl5JHNcH3SC6nS8Czii9E292XIsBtKdQijvNMn+YcmKFo6mZOUXHdO506NoKkxRny5fbKiPf/oqTA7Zx5QIDAQAB";
public static String privateRsaKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCYwvInDUICXbmWcOAR5hm86mz7WlKL3dDf12MSeIY2jm5QpUSSoMhrJOWLbOt5fXQepPaNO0M30A+3C4SFZrM/9WA5ehazO1u1m1LAkYzoSDRH3MMJsrJC3lCGDeOROteu+safuP9k/npU1YQu/+Ll2xEJNxyvUx4jLGM4LamiMI6ytM3gdnOAGP4YRQo9Etwo6I986yg/seCQC5rza9M4iBamoin7U8h9yOMKrM6xK/k9CcY/vn5+Uhe3Pvk4qj/2Ff3OXkkc1wfdILqdLwLOKL0Tb3ZciwG0p1CKO80yf5hyYoWjqZk5Rcd07nTo2gqTFGfLl9sqI9/+ipMDtnHlAgMBAAECggEATJd5yCC6lusdMRO5FOBUyUaUi9X2i1AU+RZKAynQySvSnbavUgExW58tRCHBUrGW9gJp59ft1N8J8hHhSO18NDY4H7laBlVdnwmYjRqtFo2VQO6sD4G8JRDION5f2iIxn/b2fYDI9H8vILfJRbNgtTSILyGlzTYUZzhLKxCh+8IsN96Nic8wa5COd1vZZmdhf2y8TG8clFWmozaScNSAATx7y+8XLVWjjWiIRZ6xQvx0uQPUParc9KihXXTKR2pA22yPIdz+U4MGD4kC0eczlcFKZ/dYv9e7OIGgnJfT0idSCu7nYb1pxJ1LxD9fS6IScNTF5dSe0OIL98e+XdyoAQKBgQDRep+5cW4iAKrEMH+djmcXAkoMiYtNVtnu0efLE8dP6vjYytQi368X9SdcASbfrQ31eEZmr/xQnlUF8oyHGkI38YS8dpAHzQcrkP3BljbbzB/3gJZaUdghGsDrK0xAJIzzmFKQpeKnGtr23vxUgaGrNsCYvQ0eQ7+5056KXS4r5QKBgQC6r8xtRSaje6L4WIydjWvYywsmRO0Of0aJLMDA/Wt2MWhHfh7ba9oI1cKGN80ap7xB2a9lQLgpv+C53wNtE5SpvjxsikAj96nUMMhGy9ojXrUith6HQhiINETz6Shnznd+AyrXP6KI/RpfA5nkDB5nrJxODwtYLP467IL7Cv7OAQKBgQCl4KxKdH/5fP28jYsAgJsxpSZt9xzQCU5Zxu396ZOSvUaApVyGoQpNtluMh3z48lhzYOKevgzW6gn5w69z7F8zXZT2iAxVoQ1kelP2z7RxKJrHqpNkwhqbXEwX7RlcUZUr8BqxYCqymJl7k+fMIzqaEalBSbLxnEReKi0I8/Bz4QKBgHK4b0ZCtVDHPEmimJ6E9l4dv/c/afF7swu+zaCK2ouiJvOwBCRQbYb6XPR/u/GCXASXUdpF4CX/vIhcDE3uN2/r8FO+zVWM7vbvF1OyF5WesG7pPW9e5ZZlkG3WvLa1wOZV6fCmMSo/ZwI2Q05JSDHrd43cXttLotrw1jiQ9C4BAoGBAKi4SOoOVQ5J5HQCDkBwPbG1AOLHFinzfoDl26GF/8Hy7fmmd1JiRTFldQp/A9VTAABz3sVYmMB92HSIaJhuDMoYJNI2Cf/cZifsv7vUL8cbLn+lPsKsebiuB0m0g4P2qLwLfegfNGEgA7lA5HIz3SELqbdp3iuqJeQl1fsJqD74";
public static byte[] decryptBASE64(String key) throws Exception {
return Base64.decodeBase64(key);
}
public static String encryptBASE64(byte[] key) throws Exception {
return Base64.encodeBase64String(key);
}
/**
* RSA
*
* @param keyLength 5122048
* 1024
* @return
*/
public static KeyPair generateRSAKeyPair(int keyLength) {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
*
*
* @param data
*/
public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
// 得到公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey keyPublic = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
// 加密数据
Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
cp.init(Cipher.ENCRYPT_MODE, keyPublic);
return cp.doFinal(data);
}
/**
*
*
* @param data
* @param privateKey
* @return byte[]
*/
public static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception {
// 得到私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey keyPrivate = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
// 数据加密
Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
cipher.init(Cipher.ENCRYPT_MODE, keyPrivate);
return cipher.doFinal(data);
}
/**
*
*
* @param data
* @param publicKey
* @return byte[]
*/
public static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
// 得到公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey keyPublic = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
// 数据解密
Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
cipher.init(Cipher.DECRYPT_MODE, keyPublic);
return cipher.doFinal(data);
}
/**
* 使
*/
public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {
// 得到私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey keyPrivate = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
// 解密数据
Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
cp.init(Cipher.DECRYPT_MODE, keyPrivate);
byte[] arr = cp.doFinal(encrypted);
return arr;
}
/**
*
*/
public static byte[] encryptByPublicKeyForSpilt(byte[] data, byte[] publicKey) throws Exception {
int dataLen = data.length;
if (dataLen <= DEFAULT_BUFFERSIZE) {
return encryptByPublicKey(data, publicKey);
}
List<Byte> allBytes = new ArrayList<Byte>(2048);
int bufIndex = 0;
int subDataLoop = 0;
byte[] buf = new byte[DEFAULT_BUFFERSIZE];
for (int i = 0; i < dataLen; i++) {
buf[bufIndex] = data[i];
if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
subDataLoop++;
if (subDataLoop != 1) {
for (byte b : DEFAULT_SPLIT) {
allBytes.add(b);
}
}
byte[] encryptBytes = encryptByPublicKey(buf, publicKey);
for (byte b : encryptBytes) {
allBytes.add(b);
}
bufIndex = 0;
if (i == dataLen - 1) {
buf = null;
} else {
buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
}
}
}
byte[] bytes = new byte[allBytes.size()];
{
int i = 0;
for (Byte b : allBytes) {
bytes[i++] = b.byteValue();
}
}
return bytes;
}
/**
* 使
*
* @param data
* @param privateKey
*/
public static byte[] encryptByPrivateKeyForSpilt(byte[] data, byte[] privateKey) throws Exception {
int dataLen = data.length;
if (dataLen <= DEFAULT_BUFFERSIZE) {
return encryptByPrivateKey(data, privateKey);
}
List<Byte> allBytes = new ArrayList<Byte>(2048);
int bufIndex = 0;
int subDataLoop = 0;
byte[] buf = new byte[DEFAULT_BUFFERSIZE];
for (int i = 0; i < dataLen; i++) {
buf[bufIndex] = data[i];
if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
subDataLoop++;
if (subDataLoop != 1) {
for (byte b : DEFAULT_SPLIT) {
allBytes.add(b);
}
}
byte[] encryptBytes = encryptByPrivateKey(buf, privateKey);
for (byte b : encryptBytes) {
allBytes.add(b);
}
bufIndex = 0;
if (i == dataLen - 1) {
buf = null;
} else {
buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
}
}
}
byte[] bytes = new byte[allBytes.size()];
{
int i = 0;
for (Byte b : allBytes) {
bytes[i++] = b.byteValue();
}
}
return bytes;
}
/**
*
*
* @param encrypted
* @param publicKey
*/
public static byte[] decryptByPublicKeyForSpilt(byte[] encrypted, byte[] publicKey) throws Exception {
int splitLen = DEFAULT_SPLIT.length;
if (splitLen <= 0) {
return decryptByPublicKey(encrypted, publicKey);
}
int dataLen = encrypted.length;
List<Byte> allBytes = new ArrayList<Byte>(1024);
int latestStartIndex = 0;
for (int i = 0; i < dataLen; i++) {
byte bt = encrypted[i];
boolean isMatchSplit = false;
if (i == dataLen - 1) {
// 到data的最后了
byte[] part = new byte[dataLen - latestStartIndex];
System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
byte[] decryptPart = decryptByPublicKey(part, publicKey);
for (byte b : decryptPart) {
allBytes.add(b);
}
latestStartIndex = i + splitLen;
i = latestStartIndex - 1;
} else if (bt == DEFAULT_SPLIT[0]) {
// 这个是以split[0]开头
if (splitLen > 1) {
if (i + splitLen < dataLen) {
// 没有超出data的范围
for (int j = 1; j < splitLen; j++) {
if (DEFAULT_SPLIT[j] != encrypted[i + j]) {
break;
}
if (j == splitLen - 1) {
// 验证到split的最后一位都没有break则表明已经确认是split段
isMatchSplit = true;
}
}
}
} else {
// split只有一位则已经匹配了
isMatchSplit = true;
}
}
if (isMatchSplit) {
byte[] part = new byte[i - latestStartIndex];
System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
byte[] decryptPart = decryptByPublicKey(part, publicKey);
for (byte b : decryptPart) {
allBytes.add(b);
}
latestStartIndex = i + splitLen;
i = latestStartIndex - 1;
}
}
byte[] bytes = new byte[allBytes.size()];
{
int i = 0;
for (Byte b : allBytes) {
bytes[i++] = b.byteValue();
}
}
return bytes;
}
/**
* 使
*/
public static byte[] decryptByPrivateKeyForSpilt(byte[] encrypted, byte[] privateKey) throws Exception {
int splitLen = DEFAULT_SPLIT.length;
if (splitLen <= 0) {
return decryptByPrivateKey(encrypted, privateKey);
}
int dataLen = encrypted.length;
List<Byte> allBytes = new ArrayList<Byte>(1024);
int latestStartIndex = 0;
for (int i = 0; i < dataLen; i++) {
byte bt = encrypted[i];
boolean isMatchSplit = false;
if (i == dataLen - 1) {
// 到data的最后了
byte[] part = new byte[dataLen - latestStartIndex];
System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
byte[] decryptPart = decryptByPrivateKey(part, privateKey);
for (byte b : decryptPart) {
allBytes.add(b);
}
latestStartIndex = i + splitLen;
i = latestStartIndex - 1;
} else if (bt == DEFAULT_SPLIT[0]) {
// 这个是以split[0]开头
if (splitLen > 1) {
if (i + splitLen < dataLen) {
// 没有超出data的范围
for (int j = 1; j < splitLen; j++) {
if (DEFAULT_SPLIT[j] != encrypted[i + j]) {
break;
}
if (j == splitLen - 1) {
// 验证到split的最后一位都没有break则表明已经确认是split段
isMatchSplit = true;
}
}
}
} else {
// split只有一位则已经匹配了
isMatchSplit = true;
}
}
if (isMatchSplit) {
byte[] part = new byte[i - latestStartIndex];
System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
byte[] decryptPart = decryptByPrivateKey(part, privateKey);
for (byte b : decryptPart) {
allBytes.add(b);
}
latestStartIndex = i + splitLen;
i = latestStartIndex - 1;
}
}
byte[] bytes = new byte[allBytes.size()];
{
int i = 0;
for (Byte b : allBytes) {
bytes[i++] = b.byteValue();
}
}
return bytes;
}
/**
*
*/
public static String encryptByPublicKeyForSpiltStr(String data, String publicKey) throws Exception {
byte[] encryptBytes = encryptByPublicKeyForSpilt(data.getBytes(StandardCharsets.UTF_8), publicKey.getBytes());
return encryptBASE64(encryptBytes);
}
/**
* 使
*
* @param data
* @param privateKey
*/
public static String encryptByPrivateKeyForSpiltStr(String data, String privateKey) throws Exception {
byte[] encryptBytes = encryptByPrivateKeyForSpilt(data.getBytes(StandardCharsets.UTF_8), privateKey.getBytes());
return encryptBASE64(encryptBytes);
}
/**
*
*
* @param encrypted
* @param publicKey
*/
public static String decryptByPublicKeyForSpiltStr(String encrypted, String publicKey) throws Exception {
byte[] decryptBytes = decryptByPublicKeyForSpilt(decryptBASE64(encrypted), publicKey.getBytes());
return new String(decryptBytes,StandardCharsets.UTF_8);
}
/**
* 使
*/
public static String decryptByPrivateKeyForSpiltStr(String encrypted, String privateKey) throws Exception {
byte[] decryptBytes = decryptByPrivateKeyForSpilt(decryptBASE64(encrypted), privateKey.getBytes());
return new String(decryptBytes,StandardCharsets.UTF_8);
}
public static void testEncrypt1(String content) {
//生成秘钥对
KeyPair keyPair = RSAAndroid.generateRSAKeyPair(RSAAndroid.DEFAULT_KEY_SIZE);
//公钥
PublicKey publicKey = keyPair.getPublic();
//私钥
PrivateKey privateKey = keyPair.getPrivate();
long start;
long end;
byte[] encryptBytes = new byte[0];
byte[] decryptBytes = new byte[0];
String encryStr, decryStr;
try {
System.out.println("公钥:" + encryptBASE64(RSAAndroid.publicRsaKey.getBytes()));
//公钥加密
start = System.currentTimeMillis();
encryptBytes = RSAAndroid.encryptByPublicKeyForSpilt(content.getBytes(StandardCharsets.UTF_8), RSAAndroid.publicRsaKey.getBytes());
System.out.println("testEncrypt: 公钥加密 encryptBytes:" + encryptBytes);
end = System.currentTimeMillis();
System.out.println("公钥加密耗时 cost time---->" + (end - start));
//encryStr = BASE64Encoder.encode(encryptBytes);
encryStr = encryptBASE64(encryptBytes);
// Log.e(TAG, "加密后json数据 --1-->" + encryStr);
System.out.println("加密后json数据长度 --1-->" + encryStr.length());
System.out.println("testEncrypt: encryStr:" + encryStr);
//私钥解密
System.out.println("私钥:" + encryptBASE64(RSAAndroid.privateRsaKey.getBytes()));
start = System.currentTimeMillis();
decryptBytes = RSAAndroid.decryptByPrivateKeyForSpilt(decryptBASE64(encryStr), RSAAndroid.privateRsaKey.getBytes());
decryStr = new String(decryptBytes);
System.out.println("testEncrypt: 私钥解密 decryStr:" + decryStr);
end = System.currentTimeMillis();
System.out.println("私钥解密耗时 cost time---->" + (end - start));
System.out.println("解密后json数据 --1-->" + decryStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testEncrypt2(String content) {
//生成秘钥对
KeyPair keyPair = RSAAndroid.generateRSAKeyPair(RSAAndroid.DEFAULT_KEY_SIZE);
//公钥
PublicKey publicKey = keyPair.getPublic();
//私钥
PrivateKey privateKey = keyPair.getPrivate();
long start;
long end;
byte[] encryptBytes = new byte[0];
byte[] decryptBytes = new byte[0];
String encryStr, decryStr;
try {
//私钥加密
start = System.currentTimeMillis();
encryptBytes = RSAAndroid.encryptByPrivateKeyForSpilt(content.getBytes(StandardCharsets.UTF_8), RSAAndroid.privateRsaKey.getBytes());
end = System.currentTimeMillis();
System.out.println("私钥加密密耗时 cost time---->" + (end - start));
encryStr = encryptBASE64(encryptBytes);
// Log.e(TAG, "加密后json数据 --2-->" + encryStr);
System.out.println("加密后json数据长度 --2-->" + encryStr.length());
System.out.println("testEncrypt: 私钥加密密 encryStr:" + encryStr);
//公钥解密
start = System.currentTimeMillis();
decryptBytes = RSAAndroid.decryptByPublicKeyForSpilt(decryptBASE64(encryStr), RSAAndroid.publicRsaKey.getBytes());
decryStr = new String(decryptBytes);
System.out.println("testEncrypt: 公钥解密 decryStr:" + decryStr);
end = System.currentTimeMillis();
System.out.println("公钥解密耗时 cost time---->" + (end - start));
System.out.println("解密后json数据 --2-->" + decryStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testEncrypt3(String content) {
long start;
long end;
String encryStr, decryStr;
try {
//公钥加密
System.out.println("公钥:" + RSAAndroid.publicRsaKey);
start = System.currentTimeMillis();
encryStr = RSAAndroid.encryptByPublicKeyForSpiltStr(content, RSAAndroid.publicRsaKey);
end = System.currentTimeMillis();
System.out.println("公钥加密耗时 cost time---->" + (end - start));
System.out.println("加密后json数据长度 --1-->" + encryStr.length());
System.out.println("testEncrypt: 公钥加密 encryStr:" + encryStr);
//私钥解密
System.out.println("私钥:" + RSAAndroid.privateRsaKey);
start = System.currentTimeMillis();
encryStr = "X6Ad0LpiBP7ze/cEgwGkYS53zG5ozY1Nrk2HzrrGlWqFZdyrmYihc1Fo3pjxxfOJi60zkZXguPt197vdtf2NHjtBCamvGt8DYhvfGUFP0YSod11GckQQaUslUkwPjQKTGJ46Kdy7Y2gMKK7EdEabEmTPl/XIT9fDFX/nMWgAutcQ15Gq5FRwWQH7sSVNF5bjrxxBs7Q/JwsCsU+xl0LraifUf+1O6NzCHc4ll7dmWq6EGORjaSVYka8ItuI4hhVWffcrOhY1vDqjFkY+Mzac9ppgk1nc5StMMNGyPC4OYsLkqZa5h8acK8YhSi7dpj58Lo/yJWqMmewiGDSskrcFXCNQQVJUI10H9WmD3b//98jW6cq3awLqmpoZmjuN3fm8vx1KPOCEZs2GlM7/wCEUMabV7O5EsTtRf+6pqHYTPzZfxt2lXEEJviktjguG1WI71nwg+1XyIx5tn818XiYvs0L02hi3sWpQkk/NJ4QaE3LziuCMrgDU/GcFzYLybU627yAPPPLjB9wVZGefwUdWjMtY5AzPMBa9eNjsMaHAGe2zbnopafuouwsjH+uEZd2rzT3Uacb7+pNjl94XiB/0Xhwl1n5bi6HbT3aY2jC6YbKqCp5XQaLCbuefaRVCLC6pOHmNX6NKni98/bYKQ6XfhDoA56gJAEVsAaj/a6vpzVIMsej5zDI=";
decryStr = RSAAndroid.decryptByPrivateKeyForSpiltStr(encryStr, RSAAndroid.privateRsaKey);
end = System.currentTimeMillis();
System.out.println("私钥解密耗时 cost time---->" + (end - start));
System.out.println("解密后json数据长度 --1-->" + decryStr.length());
System.out.println("testEncrypt: 私钥解密 decryStr:" + decryStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testEncrypt4(String content) {
long start;
long end;
String encryStr, decryStr;
try {
System.out.println("公钥:" + RSAAndroid.publicRsaKey);
//私钥加密
start = System.currentTimeMillis();
encryStr = RSAAndroid.encryptByPrivateKeyForSpiltStr(content, RSAAndroid.privateRsaKey);
end = System.currentTimeMillis();
System.out.println("私钥加密密耗时 cost time---->" + (end - start));
System.out.println("加密后json数据长度 --2-->" + encryStr.length());
System.out.println("testEncrypt: 私钥加密 encryStr:" + encryStr);
//公钥解密
System.out.println("私钥:" + RSAAndroid.privateRsaKey);
start = System.currentTimeMillis();
decryStr = RSAAndroid.decryptByPublicKeyForSpiltStr(encryStr, RSAAndroid.publicRsaKey);
end = System.currentTimeMillis();
System.out.println("公钥解密耗时 cost time---->" + (end - start));
System.out.println("解密后json数据 --2-->" + decryStr);
System.out.println("testEncrypt: 公钥解密 decryStr:" + decryStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
RSAAndroid.testEncrypt3("8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。");
}
}

@ -0,0 +1,66 @@
package com.rehome.adminclientappmqttserver;
import java.io.Serializable;
public class UserInfo implements Serializable {
private String date;
public String getImeinum() {
return imeinum;
}
public void setImeinum(String imeinum) {
this.imeinum = imeinum;
}
private String imeinum;
private String sysversion;
private String username;
private String password;
private String phonemodel;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhonemodel() {
return phonemodel;
}
public void setPhonemodel(String phonemodel) {
this.phonemodel = phonemodel;
}
public String getSysversion() {
return sysversion;
}
public void setSysversion(String sysversion) {
this.sysversion = sysversion;
}
}

@ -0,0 +1,29 @@
package com.rehome.adminclientappmqttserver.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @ Author : huangwenfei
* @ Date : Created in 2021/5/16 12:11
* @ Version : $1.0.0.0
* @ Description:
*/
@Configuration
public class MybatisPlusConfig {
/**
* description:
* create by: huangwenfei
* create time: 2021/5/16 12:11
* @Param: null
* @return
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
paginationInterceptor.setDialectType("mysql");
return paginationInterceptor;
}
}

@ -0,0 +1,176 @@
package com.rehome.adminclientappmqttserver.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @ Author : huangwenfei
* @ Date : Created in 2021/5/16 1:01
* @ Version : $1.0.0.0
* @ Description: Mybatis Plus
*/
public class MysqlGenerator {
/**
*
* @author huangwenfei
* Created DateTime 2021-05-18 10:20
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + "");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "");
}
/**
* Mybatis plus controller,service,dao,entity,mapper xml
* swagger3
* @author huangwenfei
* Created DateTime 2021-05-18 10:22
*/
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
//
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("huangwenfei");
gc.setOpen(false);
// service 命名方式
gc.setServiceName("%sService");
// // service impl 命名方式
// gc.setServiceImplName("%sServiceImpl");
gc.setMapperName("%sMapper");
// gc.setXmlName("%sMapper");
gc.setFileOverride(true);
gc.setActiveRecord(true);
// XML 二级缓存
gc.setEnableCache(false);
// XML ResultMap
gc.setBaseResultMap(true);
// XML columList
gc.setBaseColumnList(true);
//实体属性 Swagger2 注解
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("Skyinno251,");
dsc.setUrl("jdbc:mysql://129.211.119.207:3306/appserver?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.rehome.adminclientappmqttserver");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("dao");
pc.setServiceImpl("service.impl");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
// 生成带有Swagger注解的实体类
templateConfig.setController("templates/controller.java");
//templateConfig.setEntity("templates/controller.java.ftl");
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
strategy.setEntityLombokModel(true);
strategy.setEntityTableFieldAnnotationEnable(true);
strategy.setRestControllerStyle(true);
strategy.setEntityLombokModel(true);
// 公共父类
// strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
// 写于父类中的公共字段
// strategy.setSuperEntityColumns("id");
//strategy.setTablePrefix(new String[] { "tb_"});
strategy.setTablePrefix(pc.getModuleName() + "_");
strategy.setControllerMappingHyphenStyle(true);
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
mpg.setStrategy(strategy);
//strategy.setInclude(new String[] { "weather_realtime","weather_city","weather_type" });//表名
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}

@ -0,0 +1,20 @@
package com.rehome.adminclientappmqttserver.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @name: SecuritySecureConfig
* @desc:
* @author: gxing
* @date: 2019-06-04 18:15
**/
@Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/actuator/**");
}
}

@ -0,0 +1,40 @@
package com.rehome.adminclientappmqttserver.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @ Author : huangwenfei
* @ Date : Created in 2021/5/17 9:15
* @ Version : $1.0.0.0
* @ Description: Swagger3 UI
*/
@Configuration
public class Swagger3Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger3接口文档")
.description("更多请咨询服务开发者hwf452")
.contact(new Contact("hwf452", "http://www.baidu.com", "hwf452@163.com"))
.version("1.0")
.build();
}
}

@ -0,0 +1,30 @@
package com.rehome.adminclientappmqttserver.controller;
import com.rehome.adminclientappmqttserver.entity.User;
import com.rehome.adminclientappmqttserver.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
*
* </p>
*
* @author huangwenfei
* @since 2021-08-17
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
public void saveUser(User user){
userService.saveByUsername(user);
}
}

@ -0,0 +1,16 @@
package com.rehome.adminclientappmqttserver.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.rehome.adminclientappmqttserver.entity.User;
/**
* <p>
* Mapper
* </p>
*
* @author huangwenfei
* @since 2021-08-17
*/
public interface UserMapper extends BaseMapper<User> {
}

@ -0,0 +1,56 @@
package com.rehome.adminclientappmqttserver.entity;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author huangwenfei
* @since 2021-08-17
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@ApiModel(value="User对象", description="")
public class User extends Model<User> {
private static final long serialVersionUID = 1L;
@TableId("username")
private String username;
@TableField("password")
private String password;
@TableField("date")
private String date;
@TableField("imeinum")
private String imeinum;
@TableField("sysversion")
private String sysversion;
@TableField("phonemodel")
private String phonemodel;
@TableField("appversion")
private String appversion;
@Override
protected Serializable pkVal() {
return this.username;
}
}

@ -0,0 +1,18 @@
package com.rehome.adminclientappmqttserver.service;
import com.rehome.adminclientappmqttserver.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
*
* </p>
*
* @author huangwenfei
* @since 2021-08-17
*/
public interface UserService extends IService<User> {
public void saveByUsername(User user);
}

@ -0,0 +1,33 @@
package com.rehome.adminclientappmqttserver.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rehome.adminclientappmqttserver.entity.User;
import com.rehome.adminclientappmqttserver.dao.UserMapper;
import com.rehome.adminclientappmqttserver.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
*
* </p>
*
* @author huangwenfei
* @since 2021-08-17
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public void saveByUsername(User user) {
Wrapper<User> wrapper = new QueryWrapper<User>().lambda().eq(User::getUsername, user.getUsername());
User userDB = this.getOne(wrapper);
if(userDB!=null){
this.update(user,wrapper);
}else {
//数据库不存在这条数据,保存到数据库
this.save(user);
}
}
}

@ -0,0 +1,91 @@
package com.rehome.adminclientappmqttserver.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-27 9:35
* @description: http
*/
public class HttpURLConnectionUtil {
/**
* @date 2021-04-29 11:23
* @description: get
* @Param: urlStr geturl
*/
public static String getNetData(String urlStr) {
HttpURLConnection conn = null;
//连接成功后我们是要读取数据的 所以要有一个输入流
InputStream inputStream = null;
// 因为读取的都是文本信息 所以使用BufferedReader
BufferedReader bufferedReader = null;
//StringBuilder来把接收到的数据拼接起来
StringBuilder result = new StringBuilder();
try {
// 读取初始url 并且创建对象
URL url = new URL(urlStr);
//打开url连接
conn = (HttpURLConnection) url.openConnection();
//设置连接
//请求的方法
conn.setRequestMethod("GET");
//设置主机连接超时(单位:毫秒)
// 发送请求端 连接到 url目标地址端的时间 受距离长短和网络速度的影响
conn.setConnectTimeout(15000);
//设置从主机读取数据超时(单位:毫秒)
// 连接成功后 获取数据的时间 受数据量和服务器处理数据的影响
conn.setReadTimeout(60000);
//设置请求参数 可以指定接收json参数 服务端的key为content-type
conn.setRequestProperty("Accept", "application/json");
//发送请求
conn.connect();
//获取响应码 如果响应码不为200 表示请求不成功
if (conn.getResponseCode() != 200) {
//todo 此处应该增加异常处理手段
return "请求失败!!!";
}
//获取响应码 如果响应码为200 表示请求成功 然后可以读取数据
//获取输入流 然后读取数据
inputStream = conn.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
//逐行读取数据
String line;//用来读取数据
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
//System.out.print(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭各种流
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
}

@ -0,0 +1,68 @@
package com.rehome.adminclientappmqttserver.utils;
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-26 9:35
* @description: http
*/
public class WeatherUtil {
/**
* @date 2021-04-29 11:23
* @description: get
* @Param: url geturl
*/
public static String analysisUrl(String url){
HttpURLConnection httpConnection = null;
String output = "";
try {
URL targetUrl = new URL(url);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Content-Type",
"application/json");
InputStreamReader isr = new InputStreamReader(httpConnection
.getInputStream(),"utf-8");
BufferedReader responseBuffer = new BufferedReader(isr);
output = responseBuffer.readLine();
} catch (Exception e) {
} finally {
httpConnection.disconnect();
}
return output;
}
/**
* @date 2021-04-29 11:23
* @description: get
* @Param: url geturl
*/
public static String analysisUrlGzip(String url){
HttpURLConnection httpConnection = null;
String output = "";
try {
URL targetUrl = new URL(url);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Content-Type", "application/json");
InputStream stream = new GZIPInputStream(httpConnection.getInputStream());
output = IOUtils.toString(stream,"utf-8");
} catch (Exception e) {
} finally {
httpConnection.disconnect();
}
return output;
}
}

@ -0,0 +1,158 @@
server:
port: 8872
management:
endpoint:
health:
show-details: always
endpoints:
web:
exposure:
include: '*'
eureka:
instance:
prefer-ip-address: true
lease-renewal-interval-in-seconds: 10
health-check-url-path: /actuator/health
metadata-map:
startup: ${random.int}
user:
name: ${spring.security.user.name}
password: ${spring.security.user.password}
client:
registry-fetch-interval-seconds: 5
serviceUrl:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@eureka.master.com:8761/eureka,http://${spring.security.user.name}:${spring.security.user.password}@eureka.slave.com:8762/eureka
spring:
#redis集群
redis:
host: 127.0.0.1
port: 6379
timeout: 20000
# 集群环境打开下面注释,单机不需要打开
# cluster:
# 集群信息
# nodes: xxx.xxx.xxx.xxx:xxxx,xxx.xxx.xxx.xxx:xxxx,xxx.xxx.xxx.xxx:xxxx
# #默认值是5 一般当此值设置过大时容易报Too many Cluster redirections
# maxRedirects: 3
password:
jedis:
pool:
max-active: 8
min-idle: 0
max-idle: 8
max-wait: -1
database: 0
application:
name: admin-client-appmqttserver
security:
user:
name: admin
password: 123456
boot:
admin:
client:
instance:
metadata:
user:
name: ${spring.security.user.name}
password: ${spring.security.user.password}
username: user
password: 123456
autoconfigure:
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
dynamic:
#设置默认的数据源或者数据源组,默认值即为master
primary: master
strict: false
datasource:
master:
driver-class-name: com.mysql.jdbc.Driver #com.mysql.jdbc.Driver # 8.0 com.mysql.cj.jdbc.Driver
#url: jdbc:mysql://127.0.0.1:3306/storm?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false
url: jdbc:mysql://127.0.0.1:3306/appserver?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
username: root
password: Skyinno251,
slave:
driver-class-name: com.mysql.jdbc.Driver #com.mysql.jdbc.Driver # 8.0 com.mysql.cj.jdbc.Driver
#url: jdbc:mysql://124.156.183.8:3306/storm?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
url: jdbc:mysql://127.0.0.1:3306:3306/appserver?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
username: root
password: root
# 数据源配置
druid:
# druid连接池监控
stat-view-servlet:
enabled: true
url-pattern: /druid/*
login-username: admin
login-password: admin
# 初始化时建立物理连接的个数
initial-size: 5
# 最大连接池数量
max-active: 30
# 最小连接池数量
min-idle: 5
# 获取连接时最大等待时间,单位毫秒
max-wait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 连接保持空闲而不被驱逐的最小时间
min-evictable-idle-time-millis: 300000
# 用来检测连接是否有效的sql要求是一个查询语句
validation-query: select count(*) from dual
# 建议配置为true不影响性能并且保证安全性。申请连接的时候检测如果空闲时间大于timeBetweenEvictionRunsMillis执行validationQuery检测连接是否有效。
test-while-idle: true
# 申请连接时执行validationQuery检测连接是否有效做了这个配置会降低性能。
test-on-borrow: false
# 归还连接时执行validationQuery检测连接是否有效做了这个配置会降低性能。
test-on-return: false
# 是否缓存preparedStatement也就是PSCache。PSCache对支持游标的数据库性能提升巨大比如说oracle。在mysql下建议关闭。
pool-prepared-statements: false
# 要启用PSCache必须配置大于0当大于0时poolPreparedStatements自动触发修改为true。
max-pool-prepared-statement-per-connection-size: 50
# 配置监控统计拦截的filters去掉后监控界面sql无法统计
filters: stat,wall
# 通过connectProperties属性来打开mergeSql功能慢SQL记录
connection-properties:
druid.stat.mergeSql: true
druid.stat.slowSqlMillis: 500
# 合并多个DruidDataSource的监控数据
use-global-data-source-stat: true
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true
servlet:
multipart:
# 开启 multipart 上传功能
enabled: true
# 文件写入磁盘的阈值
file-size-threshold: 2KB
# 最大文件大小
max-file-size: 200MB
# 最大请求大小
max-request-size: 215MB
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
auto-mapping-behavior: full
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath*:mapper/**/*Mapper.xml
global-config:
# 逻辑删除配置
db-config:
# 删除前
logic-not-delete-value: 1
# 删除后
logic-delete-value: 0
logging:
level:
root: info
com.example: debug

@ -0,0 +1,141 @@
server:
port: 8872
management:
endpoint:
health:
show-details: always
endpoints:
web:
exposure:
include: '*'
eureka:
instance:
prefer-ip-address: true
lease-renewal-interval-in-seconds: 10
health-check-url-path: /actuator/health
metadata-map:
startup: ${random.int}
user:
name: ${spring.security.user.name}
password: ${spring.security.user.password}
client:
registry-fetch-interval-seconds: 5
serviceUrl:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@eureka.master.com:8761/eureka,http://${spring.security.user.name}:${spring.security.user.password}@eureka.slave.com:8762/eureka
spring:
application:
name: admin-client-appmqttserver
security:
user:
name: admin
password: Admin123456
boot:
admin:
client:
instance:
metadata:
user:
name: ${spring.security.user.name}
password: ${spring.security.user.password}
username: user
password: 123456
autoconfigure:
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
dynamic:
#设置默认的数据源或者数据源组,默认值即为master
primary: master
strict: false
datasource:
master:
driver-class-name: com.mysql.cj.jdbc.Driver #com.mysql.jdbc.Driver # 8.0 com.mysql.cj.jdbc.Driver
#url: jdbc:mysql://127.0.0.1:3306/storm?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false
#url: jdbc:mysql://192.168.2.18:3306/appserver?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
url: jdbc:mysql://127.0.0.1:3306/appserver?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
#url: jdbc:mysql://129.211.119.207:3306/appserver?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
username: root
password: Skyinno251,
slave:
driver-class-name: com.mysql.cj.jdbc.Driver #com.mysql.jdbc.Driver # 8.0 com.mysql.cj.jdbc.Driver
#url: jdbc:mysql://124.156.183.8:3306/storm?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
url: jdbc:mysql://127.0.0.1:3306/appserver?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
username: root
password: Skyinno251,
# 数据源配置
druid:
# druid连接池监控
stat-view-servlet:
enabled: true
url-pattern: /druid/*
login-username: admin
login-password: admin
# 初始化时建立物理连接的个数
initial-size: 5
# 最大连接池数量
max-active: 30
# 最小连接池数量
min-idle: 5
# 获取连接时最大等待时间,单位毫秒
max-wait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 连接保持空闲而不被驱逐的最小时间
min-evictable-idle-time-millis: 300000
# 用来检测连接是否有效的sql要求是一个查询语句
validation-query: select count(*) from dual
# 建议配置为true不影响性能并且保证安全性。申请连接的时候检测如果空闲时间大于timeBetweenEvictionRunsMillis执行validationQuery检测连接是否有效。
test-while-idle: true
# 申请连接时执行validationQuery检测连接是否有效做了这个配置会降低性能。
test-on-borrow: false
# 归还连接时执行validationQuery检测连接是否有效做了这个配置会降低性能。
test-on-return: false
# 是否缓存preparedStatement也就是PSCache。PSCache对支持游标的数据库性能提升巨大比如说oracle。在mysql下建议关闭。
pool-prepared-statements: false
# 要启用PSCache必须配置大于0当大于0时poolPreparedStatements自动触发修改为true。
max-pool-prepared-statement-per-connection-size: 50
# 配置监控统计拦截的filters去掉后监控界面sql无法统计
filters: stat,wall
# 通过connectProperties属性来打开mergeSql功能慢SQL记录
connection-properties:
druid.stat.mergeSql: true
druid.stat.slowSqlMillis: 500
# 合并多个DruidDataSource的监控数据
use-global-data-source-stat: true
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true
servlet:
multipart:
# 开启 multipart 上传功能
enabled: true
# 文件写入磁盘的阈值
file-size-threshold: 2KB
# 最大文件大小
max-file-size: 200MB
# 最大请求大小
max-request-size: 215MB
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
auto-mapping-behavior: full
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath*:mapper/**/*Mapper.xml
global-config:
# 逻辑删除配置
db-config:
# 删除前
logic-not-delete-value: 1
# 删除后
logic-delete-value: 0
logging:
level:
root: info
com.example: debug

@ -0,0 +1,43 @@
server.port=8070
spring.application.name=admin-client-appmqttserver
eureka.client.service-url.defaultZone=http://admin:123456@eureka.master.com:8761/eureka,http://admin:123456@eureka.slave.com:8762/eureka
#管理端点的端口
#management.server.port=8081
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
#管理端点绑定的网络地址
#management.server.address=127.0.0.1
#management.endpoints.web.base-path=/actuator
#management.server.servlet.context-path=/management
#最终监控端点地址http://localhost:8081/management/actuator
#spring.boot.admin.client.instance.prefer-ip=true
#spring.boot.admin.client.instance.management-base-url=
#spring.boot.admin.client.instance.management-url=http://10.0.2.21:8081/management/actuator
#spring.boot.admin.client.instance.service-base-url=http://localhost:8081
#spring.boot.admin.client.instance.service-url=http://10.0.2.21:8081/actuator
#spring.boot.admin.client.url=http://localhost:9070
spring.boot.admin.client.username=user
spring.boot.admin.client.password=123456
eureka.instance.prefer-ip-address=true
eureka.instance.lease-renewal-interval-in-seconds=10
eureka.instance.health-check-url-path=/actuator/health
eureka.instance.metadata-map.startup=${random.int}
eureka.client.registry-fetch-interval-seconds=5
#logging.file=${spring.application.name}.log
#logging.pattern.file=%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx
spring.security.user.name=admin
spring.security.user.password=123456
spring.boot.admin.client.instance.metadata.user.name=${spring.security.user.name}
spring.boot.admin.client.instance.metadata.user.password=${spring.security.user.password}
eureka.instance.metadata-map.user.name=${spring.security.user.name}
eureka.instance.metadata-map.user.password=${spring.security.user.password}

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--日志文件主目录:这里${user.home}为当前服务器用户主目录-->
<property name="LOG_HOME" value="${user.home}/admin-client-appmqttserver_log"/>
<!--日志文件主目录:这里${user.home}为当前服务器用户主目录-->
<property name="APP_NAME" value="admin-client-appmqttserver"/>
<!--输出日志到 命令行-->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!--输出日志到 日志文件-->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--设置策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件路径:这里%d{yyyyMMdd}表示按天分类日志-->
<FileNamePattern>${LOG_HOME}/%d{yyyyMMdd}/${APP_NAME}.log</FileNamePattern>
<!--日志保留天数-->
<MaxHistory>15</MaxHistory>
</rollingPolicy>
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>50MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!--此处可以调整输出日志级别 改为debug可以看到更多日志包括hiber..、system debug类型以上的的日志-->
<root level="info">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>
</configuration>

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.rehome.adminclientappmqttserver.dao.UserMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.rehome.adminclientappmqttserver.entity.User">
<id column="username" property="username" />
<result column="password" property="password" />
<result column="date" property="date" />
<result column="imeinum" property="imeinum" />
<result column="sysversion" property="sysversion" />
<result column="phonemodel" property="phonemodel" />
<result column="appversion" property="appversion" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
username, password, date, imeinum, sysversion, phonemodel
</sql>
</mapper>

@ -0,0 +1,16 @@
create table user
(
username varchar(255) not null,
password varchar(255) null,
date varchar(255) null,
imeinum varchar(50) null,
sysversion varchar(100) null,
phonemodel varchar(255) null,
constraint user_username_uindex
unique (username)
);
alter table user
add primary key (username);

@ -0,0 +1,13 @@
package com.rehome.adminclientappmqttserver;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AdminClientAppmqttserverApplicationTests {
@Test
void contextLoads() {
}
}

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

@ -0,0 +1,165 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.rehome</groupId>
<artifactId>admin-client-temperature</artifactId>
<version>1.0.0</version>
<name>admin-client-temperature</name>
<description>aadmin-client-temperature</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2020.0.3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>19.0.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.1.0</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.20</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!--sqlserver驱动 -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>11.2.0.jre8</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,69 @@
package com.rehome.adminclientappmqttserveryf;
import com.rehome.adminclientappmqttserveryf.service.TemperatureService;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.util.Map;
@EnableJpaAuditing
@EnableScheduling
@SpringBootApplication
@EnableEurekaClient
public class AdminClientTemperatureApplication implements CommandLineRunner, ApplicationContextAware {
/**
* Spring
*/
private ApplicationContext applicationContext;
/**
*/
@Resource
private TemperatureService temperatureService;
public static void main(String[] args) {
SpringApplication.run(AdminClientTemperatureApplication.class, args);
}
/**
* applicationContext(main使,mainstatic,)
* @param args
*/
@Override
public void run(String... args) throws Exception {
//在这里可以调用applicationContext了
Map<String, Object> controllers = applicationContext.getBeansWithAnnotation(RequestMapping.class);
for (Map.Entry<String, Object> entry : controllers.entrySet()) {
System.out.println("------------------------");
System.out.println(entry.getKey());//demo1Controller
}
try {
if (temperatureService != null) {
System.out.println("------------------------");
System.out.println("UseryfController is not empty");
MqttRSAClient client = new MqttRSAClient();
client.start(temperatureService);
} else {
System.out.println("UseryfController is empty");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}

@ -0,0 +1,121 @@
package com.rehome.adminclientappmqttserveryf;
import com.rehome.adminclientappmqttserveryf.service.TemperatureService;
import com.rehome.adminclientappmqttserveryf.utils.MqttSSLSocketFactory;
import com.rehome.adminclientappmqttserveryf.utils.UUIDUtil;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import javax.net.ssl.SSLSocketFactory;
import java.io.InputStream;
public class MqttRSAClient {
/**
* ip
*/
public static final String MQTT_BROKER_HOST = "ssl://119.91.158.116:8883";
/**
*
*/
public static String MQTT_CLIENT_ID = "AppServer_YF_APP_server_01";
/**
*
*/
public static String USERNAME = "admin";
/**
*
*/
public static String PASSWORD = "publish452131wW452131wW$";
/**
*
*/
public static String TOPIC_FILTER = "WifiSHT/+/SHT20";
private volatile static MqttClient mqttClient;
private static MqttConnectOptions options;
private static int qos = 0;
public MqttRSAClient(){
try {
MQTT_CLIENT_ID = UUIDUtil.getUUID();
// host为主机名clientid即连接MQTT的客户端ID一般以客户端唯一标识符表示
// MemoryPersistence设置clientid的保存形式默认为以内存保存
mqttClient = new MqttClient(MQTT_BROKER_HOST, MQTT_CLIENT_ID, new MemoryPersistence());
// 配置参数信息
options = new MqttConnectOptions();
// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录
// 这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession(false);
// 设置用户名
options.setUserName(USERNAME);
// 设置密码
options.setPassword(PASSWORD.toCharArray());
// 设置超时时间 单位为秒
options.setConnectionTimeout(10);
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线但这个方法并没有重连的机制
options.setKeepAliveInterval(20);
//断线重连
options.setAutomaticReconnect(true);
//mqtt服务器端单双向加密
InputStream caCrtFile = this.getClass().getResourceAsStream("/ssl/my_root_ca.crt");
InputStream crtFile = this.getClass().getResourceAsStream("/ssl/client.crt");
InputStream keyFile = this.getClass().getResourceAsStream("/ssl/client.key");
String password = "";
SSLSocketFactory socketFactory = MqttSSLSocketFactory.getTwoDirSocketFactory(caCrtFile,crtFile,keyFile,password);
options.setSocketFactory(socketFactory);
} catch (Exception e) {
e.printStackTrace();
}
}
public void start(TemperatureService temperatureService) {
try {
// 连接
mqttClient.connect(options);
// 订阅
mqttClient.subscribe(TOPIC_FILTER,qos);
// 设置回调
mqttClient.setCallback(new MqttCallbackExtended(){
@Override
public void connectionLost(Throwable throwable) {
System.out.println("connectionLost");
try {
mqttClient.reconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) {
String strData = new String(mqttMessage.getPayload());
System.out.println("topic:"+s);
System.out.println("Qos:"+mqttMessage.getQos());
System.out.println("message RSA:"+strData);
temperatureService.saveTemperature(strData,s);
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("deliveryComplete---------"+ iMqttDeliveryToken.isComplete());
}
@Override
public void connectComplete(boolean b, String s) {
//连接成功后调用
try {
mqttClient.subscribe(TOPIC_FILTER,qos);//具体订阅代码
} catch (MqttException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,526 @@
package com.rehome.adminclientappmqttserveryf;
/**
* @ Author : huangwenfei
* @ Date : Created in 2021/8/11 10:44
* @ Version : $1.0.0.0
* @ Description:
*/
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
public class RSAAndroid {
private static String TAG = "RSAAndroid";
public static final String RSA = "RSA";// 非对称加密密钥算法
//public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";//加密填充方式
public static final String ECB_PKCS1_PADDING = "RSA";//加密填充方式 RSA/None/PKCS1Padding
public static final int DEFAULT_KEY_SIZE = 2048;//秘钥默认长度
public static final byte[] DEFAULT_SPLIT = "#PART#".getBytes(); // 当要加密的内容超过bufferSize则采用partSplit进行分块加密
public static final int DEFAULT_BUFFERSIZE = (DEFAULT_KEY_SIZE / 8) - 11;// 当前秘钥支持加密的最大字节数
public static String publicRsaKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmMLyJw1CAl25lnDgEeYZvOps+1pSi93Q39djEniGNo5uUKVEkqDIayTli2zreX10HqT2jTtDN9APtwuEhWazP/VgOXoWsztbtZtSwJGM6Eg0R9zDCbKyQt5Qhg3jkTrXrvrGn7j/ZP56VNWELv/i5dsRCTccr1MeIyxjOC2pojCOsrTN4HZzgBj+GEUKPRLcKOiPfOsoP7HgkAua82vTOIgWpqIp+1PIfcjjCqzOsSv5PQnGP75+flIXtz75OKo/9hX9zl5JHNcH3SC6nS8Czii9E292XIsBtKdQijvNMn+YcmKFo6mZOUXHdO506NoKkxRny5fbKiPf/oqTA7Zx5QIDAQAB";
public static String privateRsaKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCYwvInDUICXbmWcOAR5hm86mz7WlKL3dDf12MSeIY2jm5QpUSSoMhrJOWLbOt5fXQepPaNO0M30A+3C4SFZrM/9WA5ehazO1u1m1LAkYzoSDRH3MMJsrJC3lCGDeOROteu+safuP9k/npU1YQu/+Ll2xEJNxyvUx4jLGM4LamiMI6ytM3gdnOAGP4YRQo9Etwo6I986yg/seCQC5rza9M4iBamoin7U8h9yOMKrM6xK/k9CcY/vn5+Uhe3Pvk4qj/2Ff3OXkkc1wfdILqdLwLOKL0Tb3ZciwG0p1CKO80yf5hyYoWjqZk5Rcd07nTo2gqTFGfLl9sqI9/+ipMDtnHlAgMBAAECggEATJd5yCC6lusdMRO5FOBUyUaUi9X2i1AU+RZKAynQySvSnbavUgExW58tRCHBUrGW9gJp59ft1N8J8hHhSO18NDY4H7laBlVdnwmYjRqtFo2VQO6sD4G8JRDION5f2iIxn/b2fYDI9H8vILfJRbNgtTSILyGlzTYUZzhLKxCh+8IsN96Nic8wa5COd1vZZmdhf2y8TG8clFWmozaScNSAATx7y+8XLVWjjWiIRZ6xQvx0uQPUParc9KihXXTKR2pA22yPIdz+U4MGD4kC0eczlcFKZ/dYv9e7OIGgnJfT0idSCu7nYb1pxJ1LxD9fS6IScNTF5dSe0OIL98e+XdyoAQKBgQDRep+5cW4iAKrEMH+djmcXAkoMiYtNVtnu0efLE8dP6vjYytQi368X9SdcASbfrQ31eEZmr/xQnlUF8oyHGkI38YS8dpAHzQcrkP3BljbbzB/3gJZaUdghGsDrK0xAJIzzmFKQpeKnGtr23vxUgaGrNsCYvQ0eQ7+5056KXS4r5QKBgQC6r8xtRSaje6L4WIydjWvYywsmRO0Of0aJLMDA/Wt2MWhHfh7ba9oI1cKGN80ap7xB2a9lQLgpv+C53wNtE5SpvjxsikAj96nUMMhGy9ojXrUith6HQhiINETz6Shnznd+AyrXP6KI/RpfA5nkDB5nrJxODwtYLP467IL7Cv7OAQKBgQCl4KxKdH/5fP28jYsAgJsxpSZt9xzQCU5Zxu396ZOSvUaApVyGoQpNtluMh3z48lhzYOKevgzW6gn5w69z7F8zXZT2iAxVoQ1kelP2z7RxKJrHqpNkwhqbXEwX7RlcUZUr8BqxYCqymJl7k+fMIzqaEalBSbLxnEReKi0I8/Bz4QKBgHK4b0ZCtVDHPEmimJ6E9l4dv/c/afF7swu+zaCK2ouiJvOwBCRQbYb6XPR/u/GCXASXUdpF4CX/vIhcDE3uN2/r8FO+zVWM7vbvF1OyF5WesG7pPW9e5ZZlkG3WvLa1wOZV6fCmMSo/ZwI2Q05JSDHrd43cXttLotrw1jiQ9C4BAoGBAKi4SOoOVQ5J5HQCDkBwPbG1AOLHFinzfoDl26GF/8Hy7fmmd1JiRTFldQp/A9VTAABz3sVYmMB92HSIaJhuDMoYJNI2Cf/cZifsv7vUL8cbLn+lPsKsebiuB0m0g4P2qLwLfegfNGEgA7lA5HIz3SELqbdp3iuqJeQl1fsJqD74";
public static byte[] decryptBASE64(String key) throws Exception {
return Base64.decodeBase64(key);
}
public static String encryptBASE64(byte[] key) throws Exception {
return Base64.encodeBase64String(key);
}
/**
* RSA
*
* @param keyLength 5122048
* 1024
* @return
*/
public static KeyPair generateRSAKeyPair(int keyLength) {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
*
*
* @param data
*/
public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
// 得到公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey keyPublic = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
// 加密数据
Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
cp.init(Cipher.ENCRYPT_MODE, keyPublic);
return cp.doFinal(data);
}
/**
*
*
* @param data
* @param privateKey
* @return byte[]
*/
public static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception {
// 得到私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey keyPrivate = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
// 数据加密
Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
cipher.init(Cipher.ENCRYPT_MODE, keyPrivate);
return cipher.doFinal(data);
}
/**
*
*
* @param data
* @param publicKey
* @return byte[]
*/
public static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
// 得到公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey keyPublic = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
// 数据解密
Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
cipher.init(Cipher.DECRYPT_MODE, keyPublic);
return cipher.doFinal(data);
}
/**
* 使
*/
public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {
// 得到私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey keyPrivate = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
// 解密数据
Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
cp.init(Cipher.DECRYPT_MODE, keyPrivate);
byte[] arr = cp.doFinal(encrypted);
return arr;
}
/**
*
*/
public static byte[] encryptByPublicKeyForSpilt(byte[] data, byte[] publicKey) throws Exception {
int dataLen = data.length;
if (dataLen <= DEFAULT_BUFFERSIZE) {
return encryptByPublicKey(data, publicKey);
}
List<Byte> allBytes = new ArrayList<Byte>(2048);
int bufIndex = 0;
int subDataLoop = 0;
byte[] buf = new byte[DEFAULT_BUFFERSIZE];
for (int i = 0; i < dataLen; i++) {
buf[bufIndex] = data[i];
if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
subDataLoop++;
if (subDataLoop != 1) {
for (byte b : DEFAULT_SPLIT) {
allBytes.add(b);
}
}
byte[] encryptBytes = encryptByPublicKey(buf, publicKey);
for (byte b : encryptBytes) {
allBytes.add(b);
}
bufIndex = 0;
if (i == dataLen - 1) {
buf = null;
} else {
buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
}
}
}
byte[] bytes = new byte[allBytes.size()];
{
int i = 0;
for (Byte b : allBytes) {
bytes[i++] = b.byteValue();
}
}
return bytes;
}
/**
* 使
*
* @param data
* @param privateKey
*/
public static byte[] encryptByPrivateKeyForSpilt(byte[] data, byte[] privateKey) throws Exception {
int dataLen = data.length;
if (dataLen <= DEFAULT_BUFFERSIZE) {
return encryptByPrivateKey(data, privateKey);
}
List<Byte> allBytes = new ArrayList<Byte>(2048);
int bufIndex = 0;
int subDataLoop = 0;
byte[] buf = new byte[DEFAULT_BUFFERSIZE];
for (int i = 0; i < dataLen; i++) {
buf[bufIndex] = data[i];
if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
subDataLoop++;
if (subDataLoop != 1) {
for (byte b : DEFAULT_SPLIT) {
allBytes.add(b);
}
}
byte[] encryptBytes = encryptByPrivateKey(buf, privateKey);
for (byte b : encryptBytes) {
allBytes.add(b);
}
bufIndex = 0;
if (i == dataLen - 1) {
buf = null;
} else {
buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
}
}
}
byte[] bytes = new byte[allBytes.size()];
{
int i = 0;
for (Byte b : allBytes) {
bytes[i++] = b.byteValue();
}
}
return bytes;
}
/**
*
*
* @param encrypted
* @param publicKey
*/
public static byte[] decryptByPublicKeyForSpilt(byte[] encrypted, byte[] publicKey) throws Exception {
int splitLen = DEFAULT_SPLIT.length;
if (splitLen <= 0) {
return decryptByPublicKey(encrypted, publicKey);
}
int dataLen = encrypted.length;
List<Byte> allBytes = new ArrayList<Byte>(1024);
int latestStartIndex = 0;
for (int i = 0; i < dataLen; i++) {
byte bt = encrypted[i];
boolean isMatchSplit = false;
if (i == dataLen - 1) {
// 到data的最后了
byte[] part = new byte[dataLen - latestStartIndex];
System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
byte[] decryptPart = decryptByPublicKey(part, publicKey);
for (byte b : decryptPart) {
allBytes.add(b);
}
latestStartIndex = i + splitLen;
i = latestStartIndex - 1;
} else if (bt == DEFAULT_SPLIT[0]) {
// 这个是以split[0]开头
if (splitLen > 1) {
if (i + splitLen < dataLen) {
// 没有超出data的范围
for (int j = 1; j < splitLen; j++) {
if (DEFAULT_SPLIT[j] != encrypted[i + j]) {
break;
}
if (j == splitLen - 1) {
// 验证到split的最后一位都没有break则表明已经确认是split段
isMatchSplit = true;
}
}
}
} else {
// split只有一位则已经匹配了
isMatchSplit = true;
}
}
if (isMatchSplit) {
byte[] part = new byte[i - latestStartIndex];
System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
byte[] decryptPart = decryptByPublicKey(part, publicKey);
for (byte b : decryptPart) {
allBytes.add(b);
}
latestStartIndex = i + splitLen;
i = latestStartIndex - 1;
}
}
byte[] bytes = new byte[allBytes.size()];
{
int i = 0;
for (Byte b : allBytes) {
bytes[i++] = b.byteValue();
}
}
return bytes;
}
/**
* 使
*/
public static byte[] decryptByPrivateKeyForSpilt(byte[] encrypted, byte[] privateKey) throws Exception {
int splitLen = DEFAULT_SPLIT.length;
if (splitLen <= 0) {
return decryptByPrivateKey(encrypted, privateKey);
}
int dataLen = encrypted.length;
List<Byte> allBytes = new ArrayList<Byte>(1024);
int latestStartIndex = 0;
for (int i = 0; i < dataLen; i++) {
byte bt = encrypted[i];
boolean isMatchSplit = false;
if (i == dataLen - 1) {
// 到data的最后了
byte[] part = new byte[dataLen - latestStartIndex];
System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
byte[] decryptPart = decryptByPrivateKey(part, privateKey);
for (byte b : decryptPart) {
allBytes.add(b);
}
latestStartIndex = i + splitLen;
i = latestStartIndex - 1;
} else if (bt == DEFAULT_SPLIT[0]) {
// 这个是以split[0]开头
if (splitLen > 1) {
if (i + splitLen < dataLen) {
// 没有超出data的范围
for (int j = 1; j < splitLen; j++) {
if (DEFAULT_SPLIT[j] != encrypted[i + j]) {
break;
}
if (j == splitLen - 1) {
// 验证到split的最后一位都没有break则表明已经确认是split段
isMatchSplit = true;
}
}
}
} else {
// split只有一位则已经匹配了
isMatchSplit = true;
}
}
if (isMatchSplit) {
byte[] part = new byte[i - latestStartIndex];
System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
byte[] decryptPart = decryptByPrivateKey(part, privateKey);
for (byte b : decryptPart) {
allBytes.add(b);
}
latestStartIndex = i + splitLen;
i = latestStartIndex - 1;
}
}
byte[] bytes = new byte[allBytes.size()];
{
int i = 0;
for (Byte b : allBytes) {
bytes[i++] = b.byteValue();
}
}
return bytes;
}
/**
*
*/
public static String encryptByPublicKeyForSpiltStr(String data, String publicKey) throws Exception {
byte[] encryptBytes = encryptByPublicKeyForSpilt(data.getBytes(StandardCharsets.UTF_8), publicKey.getBytes());
return encryptBASE64(encryptBytes);
}
/**
* 使
*
* @param data
* @param privateKey
*/
public static String encryptByPrivateKeyForSpiltStr(String data, String privateKey) throws Exception {
byte[] encryptBytes = encryptByPrivateKeyForSpilt(data.getBytes(StandardCharsets.UTF_8), privateKey.getBytes());
return encryptBASE64(encryptBytes);
}
/**
*
*
* @param encrypted
* @param publicKey
*/
public static String decryptByPublicKeyForSpiltStr(String encrypted, String publicKey) throws Exception {
byte[] decryptBytes = decryptByPublicKeyForSpilt(decryptBASE64(encrypted), publicKey.getBytes());
return new String(decryptBytes,StandardCharsets.UTF_8);
}
/**
* 使
*/
public static String decryptByPrivateKeyForSpiltStr(String encrypted, String privateKey) throws Exception {
byte[] decryptBytes = decryptByPrivateKeyForSpilt(decryptBASE64(encrypted), privateKey.getBytes());
return new String(decryptBytes,StandardCharsets.UTF_8);
}
public static void testEncrypt1(String content) {
//生成秘钥对
KeyPair keyPair = RSAAndroid.generateRSAKeyPair(RSAAndroid.DEFAULT_KEY_SIZE);
//公钥
PublicKey publicKey = keyPair.getPublic();
//私钥
PrivateKey privateKey = keyPair.getPrivate();
long start;
long end;
byte[] encryptBytes = new byte[0];
byte[] decryptBytes = new byte[0];
String encryStr, decryStr;
try {
System.out.println("公钥:" + encryptBASE64(RSAAndroid.publicRsaKey.getBytes()));
//公钥加密
start = System.currentTimeMillis();
encryptBytes = RSAAndroid.encryptByPublicKeyForSpilt(content.getBytes(StandardCharsets.UTF_8), RSAAndroid.publicRsaKey.getBytes());
System.out.println("testEncrypt: 公钥加密 encryptBytes:" + encryptBytes);
end = System.currentTimeMillis();
System.out.println("公钥加密耗时 cost time---->" + (end - start));
//encryStr = BASE64Encoder.encode(encryptBytes);
encryStr = encryptBASE64(encryptBytes);
// Log.e(TAG, "加密后json数据 --1-->" + encryStr);
System.out.println("加密后json数据长度 --1-->" + encryStr.length());
System.out.println("testEncrypt: encryStr:" + encryStr);
//私钥解密
System.out.println("私钥:" + encryptBASE64(RSAAndroid.privateRsaKey.getBytes()));
start = System.currentTimeMillis();
decryptBytes = RSAAndroid.decryptByPrivateKeyForSpilt(decryptBASE64(encryStr), RSAAndroid.privateRsaKey.getBytes());
decryStr = new String(decryptBytes);
System.out.println("testEncrypt: 私钥解密 decryStr:" + decryStr);
end = System.currentTimeMillis();
System.out.println("私钥解密耗时 cost time---->" + (end - start));
System.out.println("解密后json数据 --1-->" + decryStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testEncrypt2(String content) {
//生成秘钥对
KeyPair keyPair = RSAAndroid.generateRSAKeyPair(RSAAndroid.DEFAULT_KEY_SIZE);
//公钥
PublicKey publicKey = keyPair.getPublic();
//私钥
PrivateKey privateKey = keyPair.getPrivate();
long start;
long end;
byte[] encryptBytes = new byte[0];
byte[] decryptBytes = new byte[0];
String encryStr, decryStr;
try {
//私钥加密
start = System.currentTimeMillis();
encryptBytes = RSAAndroid.encryptByPrivateKeyForSpilt(content.getBytes(StandardCharsets.UTF_8), RSAAndroid.privateRsaKey.getBytes());
end = System.currentTimeMillis();
System.out.println("私钥加密密耗时 cost time---->" + (end - start));
encryStr = encryptBASE64(encryptBytes);
// Log.e(TAG, "加密后json数据 --2-->" + encryStr);
System.out.println("加密后json数据长度 --2-->" + encryStr.length());
System.out.println("testEncrypt: 私钥加密密 encryStr:" + encryStr);
//公钥解密
start = System.currentTimeMillis();
decryptBytes = RSAAndroid.decryptByPublicKeyForSpilt(decryptBASE64(encryStr), RSAAndroid.publicRsaKey.getBytes());
decryStr = new String(decryptBytes);
System.out.println("testEncrypt: 公钥解密 decryStr:" + decryStr);
end = System.currentTimeMillis();
System.out.println("公钥解密耗时 cost time---->" + (end - start));
System.out.println("解密后json数据 --2-->" + decryStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testEncrypt3(String content) {
long start;
long end;
String encryStr, decryStr;
try {
//公钥加密
System.out.println("公钥:" + RSAAndroid.publicRsaKey);
start = System.currentTimeMillis();
encryStr = RSAAndroid.encryptByPublicKeyForSpiltStr(content, RSAAndroid.publicRsaKey);
end = System.currentTimeMillis();
System.out.println("公钥加密耗时 cost time---->" + (end - start));
System.out.println("加密后json数据长度 --1-->" + encryStr.length());
System.out.println("testEncrypt: 公钥加密 encryStr:" + encryStr);
//私钥解密
System.out.println("私钥:" + RSAAndroid.privateRsaKey);
start = System.currentTimeMillis();
encryStr = "X6Ad0LpiBP7ze/cEgwGkYS53zG5ozY1Nrk2HzrrGlWqFZdyrmYihc1Fo3pjxxfOJi60zkZXguPt197vdtf2NHjtBCamvGt8DYhvfGUFP0YSod11GckQQaUslUkwPjQKTGJ46Kdy7Y2gMKK7EdEabEmTPl/XIT9fDFX/nMWgAutcQ15Gq5FRwWQH7sSVNF5bjrxxBs7Q/JwsCsU+xl0LraifUf+1O6NzCHc4ll7dmWq6EGORjaSVYka8ItuI4hhVWffcrOhY1vDqjFkY+Mzac9ppgk1nc5StMMNGyPC4OYsLkqZa5h8acK8YhSi7dpj58Lo/yJWqMmewiGDSskrcFXCNQQVJUI10H9WmD3b//98jW6cq3awLqmpoZmjuN3fm8vx1KPOCEZs2GlM7/wCEUMabV7O5EsTtRf+6pqHYTPzZfxt2lXEEJviktjguG1WI71nwg+1XyIx5tn818XiYvs0L02hi3sWpQkk/NJ4QaE3LziuCMrgDU/GcFzYLybU627yAPPPLjB9wVZGefwUdWjMtY5AzPMBa9eNjsMaHAGe2zbnopafuouwsjH+uEZd2rzT3Uacb7+pNjl94XiB/0Xhwl1n5bi6HbT3aY2jC6YbKqCp5XQaLCbuefaRVCLC6pOHmNX6NKni98/bYKQ6XfhDoA56gJAEVsAaj/a6vpzVIMsej5zDI=";
decryStr = RSAAndroid.decryptByPrivateKeyForSpiltStr(encryStr, RSAAndroid.privateRsaKey);
end = System.currentTimeMillis();
System.out.println("私钥解密耗时 cost time---->" + (end - start));
System.out.println("解密后json数据长度 --1-->" + decryStr.length());
System.out.println("testEncrypt: 私钥解密 decryStr:" + decryStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testEncrypt4(String content) {
long start;
long end;
String encryStr, decryStr;
try {
System.out.println("公钥:" + RSAAndroid.publicRsaKey);
//私钥加密
start = System.currentTimeMillis();
encryStr = RSAAndroid.encryptByPrivateKeyForSpiltStr(content, RSAAndroid.privateRsaKey);
end = System.currentTimeMillis();
System.out.println("私钥加密密耗时 cost time---->" + (end - start));
System.out.println("加密后json数据长度 --2-->" + encryStr.length());
System.out.println("testEncrypt: 私钥加密 encryStr:" + encryStr);
//公钥解密
System.out.println("私钥:" + RSAAndroid.privateRsaKey);
start = System.currentTimeMillis();
decryStr = RSAAndroid.decryptByPublicKeyForSpiltStr(encryStr, RSAAndroid.publicRsaKey);
end = System.currentTimeMillis();
System.out.println("公钥解密耗时 cost time---->" + (end - start));
System.out.println("解密后json数据 --2-->" + decryStr);
System.out.println("testEncrypt: 公钥解密 decryStr:" + decryStr);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
RSAAndroid.testEncrypt3("8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。8月8日晚东京国立竞技场的奥运圣火熄灭场内电子屏上打出了“ARIGATO”日语“谢谢”的罗马字。57年前的那一夜东京奥运会闭幕式大屏上留下的是“SAYONARA”日语“再见”罗马字。从告别到感谢本届奥运会对日本而言原本是一场赌上国运的体育盛事而现实却朝着与理想相反的方向一路狂奔。");
}
}

@ -0,0 +1,18 @@
package com.rehome.adminclientappmqttserveryf.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @ Author : huangwenfei
* @ Date : Created in 2023/1/31 10:09
* @ Version : $1.0.0.0
* @ Description:
*/
@RestController
public class MainController {
@GetMapping(value = "/main/echo")
public String echo(){
return "hello world";
}
}

@ -0,0 +1,19 @@
package com.rehome.adminclientappmqttserveryf.dao;
import com.rehome.adminclientappmqttserveryf.entity.Temperature;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* T :
* ID :OID
*
*/
public interface TemperatureRepository extends JpaRepository<Temperature,Long> {
//方法名称必须要遵循驼峰式命名规则findBy关键字+属性名称(首字母大写)+查询条件(首字母大写)
Temperature findByDataDate(String dataDate);
Temperature findByDataHour(String dataHour);
Temperature findByDataMinute(String dataMinute);
}

@ -0,0 +1,52 @@
package com.rehome.adminclientappmqttserveryf.entity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.annotations.Proxy;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@EntityListeners(AuditingEntityListener.class)
@Proxy(lazy = false)
@Data
@Entity
public class Temperature implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@ApiModelProperty(value = "主键")
private Long id;
@ApiModelProperty(value = "温度")
private Double temperature;
@ApiModelProperty(value = "湿度")
private Double humidity;
@ApiModelProperty(value = "日期")
@Column(length=20)
private String dataDate;
@ApiModelProperty(value = "时")
@Column(length=20)
private String dataHour;
@ApiModelProperty(value = "分")
@Column(length=20)
private String dataMinute;
@ApiModelProperty(value = "主题")
@Column(length=60)
private String topic;
@ApiModelProperty(value = "位置描述")
@Column(length=80)
private String locationDesc;
@ApiModelProperty(value = "时间")
@Temporal(TemporalType.TIMESTAMP)
private Date createDate;
}

@ -0,0 +1,17 @@
package com.rehome.adminclientappmqttserveryf.service;
import org.springframework.stereotype.Component;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-26 14:35
* @description:
*/
@Component
public class ScheduledService {
}

@ -0,0 +1,6 @@
package com.rehome.adminclientappmqttserveryf.service;
public interface TemperatureService {
//温度和湿度
void saveTemperature(String temperatureAndHumidityData,String topic);
}

@ -0,0 +1,53 @@
package com.rehome.adminclientappmqttserveryf.service.impl;
import com.rehome.adminclientappmqttserveryf.dao.TemperatureRepository;
import com.rehome.adminclientappmqttserveryf.entity.Temperature;
import com.rehome.adminclientappmqttserveryf.service.TemperatureService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class TemperatureServiceImpl implements TemperatureService {
@Resource
private TemperatureRepository temperatureRepository;
@Override
public void saveTemperature(String temperatureAndHumidityData,String topic) {
if(temperatureAndHumidityData!=null&&temperatureAndHumidityData.length()>0){
String[] strDataTemperature = temperatureAndHumidityData.split(" ");
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdfHour = new SimpleDateFormat("yyyy-MM-dd HH");
SimpleDateFormat sdfMinute = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String nowDate = sdf.format(now);
String nowHour = sdfHour.format(now);
String dataMinute = sdfMinute.format(now);
Temperature temperature = new Temperature();
temperature.setCreateDate(now);
temperature.setDataDate(nowDate);
temperature.setDataHour(nowHour);
temperature.setDataMinute(dataMinute);
if(topic!=null){
temperature.setTopic(topic);
if(topic.equals("WifiSHT/7C87CE9CA4E6/SHT20")){
temperature.setLocationDesc("广东省珠海市高新区唐家湾镇东岸村水风三街28号501");
}
if(topic.equals("WifiSHT/7C87CE9F5CBF/SHT20")){
temperature.setLocationDesc("广东省中山市坦洲镇金斗新村7号东座602");
}
if(topic.equals("WifiSHT/4CEBD686B6AA/SHT20")){
temperature.setLocationDesc("广西壮族自治区崇左市天等县天等镇荣华村弄在屯113号");
}
}
temperature.setHumidity(Double.valueOf(strDataTemperature[0]));
temperature.setTemperature(Double.valueOf(strDataTemperature[1]));
this.temperatureRepository.save(temperature);
}
}
}

@ -0,0 +1,91 @@
package com.rehome.adminclientappmqttserveryf.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-27 9:35
* @description: http
*/
public class HttpURLConnectionUtil {
/**
* @date 2021-04-29 11:23
* @description: get
* @Param: urlStr geturl
*/
public static String getNetData(String urlStr) {
HttpURLConnection conn = null;
//连接成功后我们是要读取数据的 所以要有一个输入流
InputStream inputStream = null;
// 因为读取的都是文本信息 所以使用BufferedReader
BufferedReader bufferedReader = null;
//StringBuilder来把接收到的数据拼接起来
StringBuilder result = new StringBuilder();
try {
// 读取初始url 并且创建对象
URL url = new URL(urlStr);
//打开url连接
conn = (HttpURLConnection) url.openConnection();
//设置连接
//请求的方法
conn.setRequestMethod("GET");
//设置主机连接超时(单位:毫秒)
// 发送请求端 连接到 url目标地址端的时间 受距离长短和网络速度的影响
conn.setConnectTimeout(15000);
//设置从主机读取数据超时(单位:毫秒)
// 连接成功后 获取数据的时间 受数据量和服务器处理数据的影响
conn.setReadTimeout(60000);
//设置请求参数 可以指定接收json参数 服务端的key为content-type
conn.setRequestProperty("Accept", "application/json");
//发送请求
conn.connect();
//获取响应码 如果响应码不为200 表示请求不成功
if (conn.getResponseCode() != 200) {
//todo 此处应该增加异常处理手段
return "请求失败!!!";
}
//获取响应码 如果响应码为200 表示请求成功 然后可以读取数据
//获取输入流 然后读取数据
inputStream = conn.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
//逐行读取数据
String line;//用来读取数据
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
//System.out.print(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭各种流
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
}

@ -0,0 +1,90 @@
package com.rehome.adminclientappmqttserveryf.utils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
public class MqttSSLSocketFactory {
public static SSLSocketFactory getSingleSocketFactory(InputStream caCrtFileInputStream) throws Exception {
Security.addProvider(new BouncyCastleProvider());
X509Certificate caCert = null;
BufferedInputStream bis = new BufferedInputStream(caCrtFileInputStream);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
caCert = (X509Certificate) cf.generateCertificate(bis);
}
KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
caKs.load(null, null);
caKs.setCertificateEntry("cert-certificate", caCert);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(caKs);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, tmf.getTrustManagers(), null);
return sslContext.getSocketFactory();
}
public static SSLSocketFactory getTwoDirSocketFactory(InputStream caCrtFile, InputStream crtFile, InputStream keyFile,
String password) throws Exception {
Security.addProvider(new BouncyCastleProvider());
// load CA certificate
X509Certificate caCert = null;
BufferedInputStream bis = new BufferedInputStream(caCrtFile);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
caCert = (X509Certificate) cf.generateCertificate(bis);
}
// load client certificate
bis = new BufferedInputStream(crtFile);
X509Certificate cert = null;
while (bis.available() > 0) {
cert = (X509Certificate) cf.generateCertificate(bis);
}
// load client private cert
PEMParser pemParser = new PEMParser(new InputStreamReader(keyFile));
Object object = pemParser.readObject();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
KeyPair key = converter.getKeyPair((PEMKeyPair) object);
KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
caKs.load(null, null);
caKs.setCertificateEntry("cert-certificate", caCert);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(caKs);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
ks.setCertificateEntry("certificate", cert);
ks.setKeyEntry("private-cert", key.getPrivate(), password.toCharArray(),
new java.security.cert.Certificate[]{cert});
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, password.toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return sslContext.getSocketFactory();
}
}

@ -0,0 +1,9 @@
package com.rehome.adminclientappmqttserveryf.utils;
import java.util.UUID;
public class UUIDUtil {
public static String getUUID() {
return UUID.randomUUID().toString();
}
}

@ -0,0 +1,68 @@
package com.rehome.adminclientappmqttserveryf.utils;
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-26 9:35
* @description: http
*/
public class WeatherUtil {
/**
* @date 2021-04-29 11:23
* @description: get
* @Param: url geturl
*/
public static String analysisUrl(String url){
HttpURLConnection httpConnection = null;
String output = "";
try {
URL targetUrl = new URL(url);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Content-Type",
"application/json");
InputStreamReader isr = new InputStreamReader(httpConnection
.getInputStream(),"utf-8");
BufferedReader responseBuffer = new BufferedReader(isr);
output = responseBuffer.readLine();
} catch (Exception e) {
} finally {
httpConnection.disconnect();
}
return output;
}
/**
* @date 2021-04-29 11:23
* @description: get
* @Param: url geturl
*/
public static String analysisUrlGzip(String url){
HttpURLConnection httpConnection = null;
String output = "";
try {
URL targetUrl = new URL(url);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Content-Type", "application/json");
InputStream stream = new GZIPInputStream(httpConnection.getInputStream());
output = IOUtils.toString(stream,"utf-8");
} catch (Exception e) {
} finally {
httpConnection.disconnect();
}
return output;
}
}

@ -0,0 +1,71 @@
server:
port: 8873
management:
endpoint:
health:
show-details: always
endpoints:
web:
exposure:
include: '*'
eureka:
instance:
prefer-ip-address: true
lease-renewal-interval-in-seconds: 10
health-check-url-path: /actuator/health
metadata-map:
startup: ${random.int}
user:
name: ${spring.security.user.name}
password: ${spring.security.user.password}
client:
registry-fetch-interval-seconds: 5
serviceUrl:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@eureka.master.com:8761/eureka,http://${spring.security.user.name}:${spring.security.user.password}@eureka.slave.com:8762/eureka
spring:
application:
name: admin-client-temperature
security:
user:
name: admin
password: Admin123456
boot:
admin:
client:
instance:
metadata:
user:
name: ${spring.security.user.name}
password: ${spring.security.user.password}
username: user
password: 123456
datasource:
type: com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.cj.jdbc.Driver #com.mysql.cj.jdbc.Driver com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/appserver?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
username: root
password: Skyinno251,
# driverClassName: oracle.jdbc.driver.OracleDriver
# url: jdbc:oracle:thin:@192.168.2.18:1521/orcl
# username: maximo
# password: maximo
jpa:
database: mysql # 配置 DBMS 类型
show-sql: true # 配置是否将执行的 SQL 输出到日志
open-in-view: true
hibernate:
ddl-auto: update # 第一次建表create 后面用update要不然每次重启都会新建表
servlet:
multipart:
# 开启 multipart 上传功能
enabled: true
# 文件写入磁盘的阈值
file-size-threshold: 2KB
# 最大文件大小
max-file-size: 200MB
# 最大请求大小
max-request-size: 215MB
logging:
level:
root: info
com.example: debug

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--日志文件主目录:这里${user.home}为当前服务器用户主目录-->
<property name="LOG_HOME" value="${user.home}/admin-client-temperature_log"/>
<!--日志文件主目录:这里${user.home}为当前服务器用户主目录-->
<property name="APP_NAME" value="admin-client-temperature"/>
<!--输出日志到 命令行-->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!--输出日志到 日志文件-->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--设置策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件路径:这里%d{yyyyMMdd}表示按天分类日志-->
<FileNamePattern>${LOG_HOME}/%d{yyyyMMdd}/${APP_NAME}.log</FileNamePattern>
<!--日志保留天数-->
<MaxHistory>15</MaxHistory>
</rollingPolicy>
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>50MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!--此处可以调整输出日志级别 改为debug可以看到更多日志包括hiber..、system debug类型以上的的日志-->
<root level="info">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>
</configuration>

@ -0,0 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA4omYWBuiZ2bPhpmZFuvX50FMP07k/rI4uajLT1irRwoUn0ZR
xLO+voWb+0pMnLH6Aq/ehBW+WVOn4eQ4BBpSNXm4n5tJo71+FKKMk0uaX7NnBJ+P
FJxJxoBn5kFNAXUWdDojCTVMBX3k/QG679n6bYzzguk5Ky/pIEvePleox49MJJ5W
C3fHWNMODhWEYJXGgxjCSmWynLPmEdOyi2/KfKfplgCx1NYPbPW1JtZSRjJ9zK6b
5g2uGts50JEDuWAkYXpztAetaBF68+h79aHKP78AAHRa+0cT+4J1uxwcf9XK7fQt
5UGkuDZpUVWjQ9a44ciwaAXcKy9hqYRfSm9GBQIDAQABAoIBAQDCVBxOgK4pG2Ws
ZjiQFBJqe3ZH3IrN/d5xTV3SnBKZZwlXtD/SiAp5by3mO89Kn9YC1hEAp5JZGE0s
ltSCmH2rB9abe9+IybXNR79lX3Z23/PgYGuh14vl7yKxv5SqSmHPpEuHy6OCFoQH
kaNlu0x7C22dACodZQULwmlMe2/6dtHQbs9x0OROnJa9SpnScXfaPW/g/ONqR7S1
rytHsM8dWUSEvNCUBqGqUFCTBPX44+w1RBLji36ZP1zeenlcBSMGlBifVJKH5OCk
MFR33iwh3BXxIi+he+DGBX8c1CRplgfitQZlSnX5I0OXcBm1r0I9zrC2hs1w4WVd
KNpr556FAoGBAPxqeqp7UaVfSQOMLQrpFAEBP6sqYd9dM3S81COpEB0i1i/6eZiE
dPiP92OXp5Ka3/0pT0h66K+enkmKQ788OaGtJpz6KIU25ZRN+t+tS4UslFg67BY5
bdFad2pIF2Ql89EzqCmzHz6q2xc0SD467jEPS4FcNf8G91lJvamuLYkvAoGBAOXB
DIP8FiF3jn0DaoQpv3sX4R9UKNXOcaJmaprVZ5VHml8vrszrKju2HogKtyEzCMiS
I+MBSg9Vum5n9MFHUd/eRAqV1oh3l2QsR0AEJe230xXotoZ8Vdid32JNtsnR7YRL
q/OcMFhdpk50J8cVlx3gnC61S54jl1pAEFWSMW8LAoGATjZkKf0qMFbVFe9SaaYN
F76eTthEGWUUs6BrD12sa4rG2XkAQn0QjZB2dHqiZu/sZdJuCaRkAz7gByN7mH79
0JYJd+yfr59yBcEf8j0NQIeus6QWUVCcMZmZlOofrV2BLhqWic1B6jYgyxDdLcMu
2S7HE59R7+Lls9oAldotq+sCgYEAhd6IFldJ5dItufXFmKBiq6xsRb7Z1Epnt8KJ
FxKFOlvwPMohxdC4WPZyr73emn+L/KH6OwjDSFAhQrdby0ptEE4Hw0svJ3DXS0zp
bwl7uBlF6xwfThkgRAko4bR6bvnctRsKY/V7zeEzR78ydjPES2pWVnjYSJpgU/vE
CLgYCaUCgYBzgGR2IrTfGdu9TVkEt9dAYS2QKwI+iEpTBLdJBCPiXbfg1Jh8xH5t
vmFOYQPnvyu6cRg9JQFXAVmEHcjC0VPwy/wURxVcgw1il/zmUrUAERVhpG/4uC4N
XQK0ipg/gvSEJKyiqeQN+nLv0PrdQ9vCQSG9sSMvWHL6dTcQDeNDiw==
-----END RSA PRIVATE KEY-----

@ -0,0 +1,13 @@
package com.rehome.adminclientappmqttserveryf;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AdminClientAppmqttserverYfApplicationTests {
@Test
void contextLoads() {
}
}

@ -0,0 +1,29 @@
HELP.md
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
/build/
### VS Code ###
.vscode/

@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springcloud.adminclient</groupId>
<artifactId>admin-client</artifactId>
<version>0.0.1</version>
<name>admin-client</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,13 @@
package com.springcloud.adminclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AdminClientApplication {
public static void main(String[] args) {
SpringApplication.run(AdminClientApplication.class, args);
}
}

@ -0,0 +1,20 @@
package com.springcloud.adminclient.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @name: SecuritySecureConfig
* @desc:
* @author: gxing
* @date: 2019-06-04 18:15
**/
@Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/actuator/**");
}
}

@ -0,0 +1,23 @@
package com.springcloud.adminclient.controller;
import com.springcloud.adminclient.entity.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
/**
* @name: StudentController
* @desc: TODO
* @author: gxing
* @date: 2019-06-05 16:07
**/
@RestController
@RequestMapping("/stu")
public class StudentController {
@RequestMapping("/getStudent")
public Student getStudent(){
return new Student(12,new Date());
}
}

@ -0,0 +1,44 @@
package com.springcloud.adminclient.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
* @name: Student
* @desc: TODO
* @author: gxing
* @date: 2019-06-05 16:06
**/
public class Student {
private Integer id;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date birthday;
public Student() {
}
public Student(Integer id, Date birthday) {
this.id = id;
this.birthday = birthday;
}
public Integer getId() {
return id;
}
public Student setId(Integer id) {
this.id = id;
return this;
}
public Date getBirthday() {
return birthday;
}
public Student setBirthday(Date birthday) {
this.birthday = birthday;
return this;
}
}

@ -0,0 +1,44 @@
server.port=8070
spring.application.name=admin-client
eureka.environment=prod
eureka.instance.hostname=localhost
eureka.client.service-url.defaultZone=http://admin:123456@eureka.master.com:8761/eureka,http://admin:123456@eureka.slave.com:8762/eureka
#管理端点的端口
#management.server.port=8081
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
#管理端点绑定的网络地址
#management.server.address=127.0.0.1
#management.endpoints.web.base-path=/actuator
#management.server.servlet.context-path=/management
#最终监控端点地址http://localhost:8081/management/actuator
#spring.boot.admin.client.instance.prefer-ip=true
#spring.boot.admin.client.instance.management-base-url=
#spring.boot.admin.client.instance.management-url=http://10.0.2.21:8081/management/actuator
#spring.boot.admin.client.instance.service-base-url=http://localhost:8081
#spring.boot.admin.client.instance.service-url=http://10.0.2.21:8081/actuator
#spring.boot.admin.client.url=http://localhost:9070
spring.boot.admin.client.username=user
spring.boot.admin.client.password=123456
eureka.instance.prefer-ip-address=true
eureka.instance.lease-renewal-interval-in-seconds=10
eureka.instance.health-check-url-path=/actuator/health
eureka.instance.metadata-map.startup=${random.int}
eureka.client.registry-fetch-interval-seconds=5
logging.file=${spring.application.name}.log
#logging.pattern.file=%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx
spring.security.user.name=admin
spring.security.user.password=123456
spring.boot.admin.client.instance.metadata.user.name=${spring.security.user.name}
spring.boot.admin.client.instance.metadata.user.password=${spring.security.user.password}
eureka.instance.metadata-map.user.name=${spring.security.user.name}
eureka.instance.metadata-map.user.password=${spring.security.user.password}

@ -0,0 +1,16 @@
package com.springcloud.adminclient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AdminClientApplicationTests {
@Test
public void contextLoads() {
}
}

@ -0,0 +1,29 @@
HELP.md
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
/build/
### VS Code ###
.vscode/

@ -0,0 +1,84 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springcloud.adminserver</groupId>
<artifactId>admin-server</artifactId>
<version>0.0.1</version>
<name>admin-server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,15 @@
package com.springcloud.adminserver;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableAdminServer
public class AdminServerApplication {
public static void main(String[] args) {
SpringApplication.run(AdminServerApplication.class, args);
}
}

@ -0,0 +1,21 @@
package com.springcloud.adminserver.config;
/**
* @name: HazelcastConfig
* @desc: TODO
* @author: gxing
* @date: 2019-06-05 10:02
**/
/*
@Configuration
public class HazelcastConfig {
@Bean
public Config hazelcastConfig() {
MapConfig mapConfig = new MapConfig("spring-boot-admin-event-store").setInMemoryFormat(InMemoryFormat.OBJECT)
.setBackupCount(1)
.setEvictionPolicy(EvictionPolicy.NONE)
.setMergePolicyConfig(new MergePolicyConfig(PutIfAbsentMapMergePolicy.class.getName(), 100));
return new Config().setProperty("hazelcast.jmx", "true").addMapConfig(mapConfig);
}
}*/

@ -0,0 +1,55 @@
package com.springcloud.adminserver.config;
import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
/**
* @name: SecuritySecureConfig
* @desc: TODO
* @author: gxing
* @date: 2019-06-04 17:17
**/
@Configuration
public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
private final String adminContextPath;
public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
this.adminContextPath = adminServerProperties.getContextPath();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(adminContextPath + "/");
http.authorizeRequests()
//放行静态资源
.antMatchers(adminContextPath + "/assets/**").permitAll()
.antMatchers(adminContextPath + "/login").permitAll()
//对每个请求认证
.anyRequest().authenticated()
.and()
//登录和注销
.formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
.logout().logoutUrl(adminContextPath + "/logout").and()
//启用HTTP-Basic支持。Spring Boot Admin Client注册必需的。
.httpBasic().and()
.csrf()
//使用Cookie启用CSRF保护
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringAntMatchers(
//禁用CRSF-Protection Spring Boot Admin Client用于注册的端点。
adminContextPath + "/instances",
//禁用执行器端点的CRSF保护。
adminContextPath + "/actuator/**"
);
// @formatter:on
}
}

@ -0,0 +1,12 @@
server.port=9070
spring.application.name=admin-server
eureka.environment=prod
eureka.instance.hostname=192.168.1.5
eureka.client.service-url.defaultZone=http://admin:123456@eureka.master.com:8761/eureka,http://admin:123456@eureka.slave.com:8762/eureka
spring.security.user.name=user
spring.security.user.password=123456
eureka.instance.metadata-map.user.name=${spring.security.user.name}
eureka.instance.metadata-map.user.password=${spring.security.user.password}
eureka.instance.health-check-url-path=/actuator/health

@ -0,0 +1,16 @@
package com.springcloud.adminserver;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootAdminApplicationTests {
@Test
public void contextLoads() {
}
}

@ -0,0 +1,29 @@
HELP.md
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
/build/
### VS Code ###
.vscode/

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springcloud.commons</groupId>
<artifactId>commons-jar</artifactId>
<version>0.0.1</version>
<name>commons-jar</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--java-jwt-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.10</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.0.1-jre</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,13 @@
package com.springcloud.commons;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CommonsJarApplication {
public static void main(String[] args) {
SpringApplication.run(CommonsJarApplication.class, args);
}
}

@ -0,0 +1,42 @@
package com.springcloud.commons.bean;
import java.io.Serializable;
/**
* @name: JwtToken
* @desc: JWT
* @author: gxing
* @date: 2019-05-30 14:00
**/
public class JwtToken implements Serializable {
private static final long serialVersionUID = 7780238154438192887L;
private String jwtId;
private String token;
public JwtToken() {
}
public JwtToken(String jwtId, String token) {
this.jwtId = jwtId;
this.token = token;
}
public String getJwtId() {
return jwtId;
}
public JwtToken setJwtId(String jwtId) {
this.jwtId = jwtId;
return this;
}
public String getToken() {
return token;
}
public JwtToken setToken(String token) {
this.token = token;
return this;
}
}

@ -0,0 +1,20 @@
package com.springcloud.commons.bean;
/**
* @name: ResponseCode
* @desc: TODO
* @author: gxing
* @date: 2019-05-27 11:43
**/
public class ResponseCode {
/*成功/正确 编码*/
public static final int SUCCESS_CODE = 200;
/*失败/错误 编码*/
public static final int TOKEN_TIME_OUT = 401;
public static final int NO_AUTO = 402;
public static final int SIGN_ERROR = 402;
public static final int PARAM_IS_NULL = 403;
public static final int PARAM_IS_ERROR = 404;
}

@ -0,0 +1,94 @@
package com.springcloud.commons.bean;
import java.io.Serializable;
/**
* @name: ResultBean
* @desc: TODO
* @author: gxing
* @date: 2019-05-27 14:06
**/
public class ResultBean implements Serializable {
private static final long serialVersionUID = -1936178861383421225L;
private static final String STATE_SUCCESS = "success";
private static final String STATE_FAIL = "fail";
private static final Integer CODE_SUCCESS = 200;
private static final Integer CODE_FAIL = 400;
private Integer code;
private String state;
private String msg;
private Object date;
public ResultBean() {
}
public ResultBean(String state, Integer code, String msg, Object date) {
this.state = state;
this.code = code;
this.msg = msg;
this.date = date;
}
public ResultBean success() {
this.state = STATE_SUCCESS;
this.code = CODE_SUCCESS;
return this;
}
public ResultBean fial() {
this.state = STATE_FAIL;
this.code = CODE_FAIL;
return this;
}
public ResultBean fialByNullParam() {
this.state = STATE_FAIL;
this.code = ResponseCode.PARAM_IS_NULL;
return this;
}
public ResultBean fialByErrorParam() {
this.state = STATE_FAIL;
this.code = ResponseCode.PARAM_IS_ERROR;
return this;
}
public String getState() {
return state;
}
public ResultBean setState(String state) {
this.state = state;
return this;
}
public Integer getCode() {
return code;
}
public ResultBean setCode(Integer code) {
this.code = code;
return this;
}
public String getMsg() {
return msg;
}
public ResultBean setMsg(String msg) {
this.msg = msg;
return this;
}
public Object getDate() {
return date;
}
public ResultBean setDate(Object date) {
this.date = date;
return this;
}
}

@ -0,0 +1,161 @@
package com.springcloud.commons.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
/**
* @name: JavaJwtUtil
* @desc: java_jwt ,token
* @author: gxing
* @date: 2019-05-27 11:11
**/
public class JavaJwtUtil {
/*默认有效期 1天 = 24小时*/
private static final Long END_DATETIME = System.currentTimeMillis() + 1000 * 60 * 1440;
private static RSAPrivateKey rsaPrivateKey = RSAUtil.getPrivateKey(RSAUtil.MODULUS, RSAUtil.PRIVATE_EXPONENT);
private static RSAPublicKey rsaPublicKey = RSAUtil.getPublicKey(RSAUtil.MODULUS, RSAUtil.PUBLIC_EXPONENT);
/**
* HMAC256 Token
*
* @param jwtId id
* @param secret
* @return String
*/
public static String getTokenByHMAC256(String jwtId, String secret) {
String token = JWT.create()
.withClaim("jwtId", jwtId)
.withExpiresAt(new Date(END_DATETIME))
.sign(Algorithm.HMAC256(secret));
return token;
}
/**
* HMAC256 Token
*
* @param jwtId id
* @param exp ,:
* @param secret
* @return String
*/
public static String getTokenByHMAC256(String jwtId, int exp, String secret) {
Long endDateTime = System.currentTimeMillis() + 1000 * 60 * exp;
String token = JWT.create()
.withClaim("jwtId", jwtId)
.withExpiresAt(new Date(endDateTime))
.sign(Algorithm.HMAC256(secret));
return token;
}
/**
* RSA512 Token
*
* @param jwtId ID
* @return String
*/
public static String getTokenByRSA512(String jwtId) {
Algorithm algorithm = Algorithm.RSA512(rsaPublicKey, rsaPrivateKey);
String token = JWT.create()
.withClaim("jwtId", jwtId)
.withExpiresAt(new Date(END_DATETIME))
.sign(algorithm);
return token;
}
/**
* RSA512 Token
*
* @param jwtId id
* @param exp
* @return String
*/
public static String getTokenByRSA512(String jwtId, int exp) {
Long endDateTime = System.currentTimeMillis() + 1000 * 60 * exp;
Algorithm algorithm = Algorithm.RSA512(rsaPublicKey, rsaPrivateKey);
String token = JWT.create()
.withClaim("jwtId", jwtId)
.withExpiresAt(new Date(endDateTime))
.sign(algorithm);
return token;
}
/**
* HMAC256 Token
*
* @param token
* @param jwtId id
* @param secret
* @return boolean
*/
public static boolean verifyTokenByHMAC256(String token, String jwtId, String secret) {
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret))
.withClaim("jwtId", jwtId).build();
return verifyToken(token, jwtVerifier);
}
/**
* RSA512 Token
*
* @param token
* @param jwtId ID
* @return boolean
*/
public static boolean verifyTokenByRSA512(String token, String jwtId) {
JWTVerifier jwtVerifier = JWT.require(Algorithm.RSA512(rsaPublicKey, rsaPrivateKey))
.withClaim("jwtId", jwtId).build();
return verifyToken(token, jwtVerifier);
}
/**
* Token
*
* @param token
* @param jwtVerifier JWTVerifier
* @return boolean
*/
private static boolean verifyToken(String token, JWTVerifier jwtVerifier) {
try {
jwtVerifier.verify(token);
return true;
} catch (JWTVerificationException e) {
throw e;
// return false;
}
}
/*
public static void main(String[] args) {
String token1 = JavaJwtUtil.getTokenByHMAC256("1001", 60, "AABBCCDD");
System.out.println(token1);
String token2 = JavaJwtUtil.getTokenByHMAC256("1001", "aabbccdd");
System.out.println(token2);
boolean check = JavaJwtUtil.verifyTokenByHMAC256(token2, "1001", "aabbccdd");
System.out.println(check);
String tokenByRSA = JavaJwtUtil.getTokenByRSA512("1001");
String tokenByRSA = JavaJwtUtil.getTokenByRSA512("1001", 1);
System.out.println(tokenByRSA);
boolean check = JavaJwtUtil.verifyTokenByRSA512(tokenByRSA, "1001");
System.out.println(check);
}
*/
}

@ -0,0 +1,311 @@
package com.springcloud.commons.util;
import javax.crypto.Cipher;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
/**
* @name: RSAUtil
* @desc: RSA
* @author: gxing
* @date: 2019-05-27 13:57
**/
public class RSAUtil {
public static String RSA_ALGORITHM = "RSA";
/*模数*/
public static String MODULUS = "20699446869743660585652600085521142545885549299416180356907337174876844447072851354250340617493097256523250986258369631674290919786602738236384133455968402973562638944860676845409357141185806086950114923982834902384649504957498323265843637180622659201493542601941446721829110515477834357151021180476489881513326425639917146332982689679883343585484994645969500826856802047685314244182936770833959865758239998395155286496069770257369754869757955696448390476954823903148723590343746389325432308943023017334156517775392772516273846119705893987401809697466747196964354573931365227853281877988902285243625430107129364655677";
/*公钥指数*/
public static String PUBLIC_EXPONENT = "65537";
/*私钥指数*/
public static String PRIVATE_EXPONENT = "7752382980878864596713964159163776855650408281645027188615447624354977294557320849139792948355403392913364900097833019659817669807317457466958337361745951920077131588287613305012018722712446563074150034471499804370526909977292160833729527970434764638305979876476689652979164710047811836005185084376694754745220717141834721991812378949309261576714952224857443411317481019886585010389914550136482822295477704937979041224302405587417950544740345790835101577186170938604199681751873488184019865981053862812821750153385594250488559776169734914538021236458801817027632992427894939524367338782478952238328781398876966625473";
/**
*
* @param data
* @return
* @throws Exception
*/
public static String encryptByPublicKey(String data) throws Exception {
RSAPublicKey publicKey = RSAUtil.getPublicKey(MODULUS, PUBLIC_EXPONENT);
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 模长
int key_len = publicKey.getModulus().bitLength() / 8;
// 加密数据长度 <= 模长-11
String[] datas = splitString(data, key_len - 11);
String mi = "";
// 如果明文长度大于模长-11则要分组加密
for (String s : datas) {
mi += bcd2Str(cipher.doFinal(s.getBytes()));
}
return mi;
}
/**
*
* @param data
* @return
* @throws Exception
*/
public static String decryptByPrivateKey(String data) throws Exception {
RSAPrivateKey privateKey = RSAUtil.getPrivateKey(MODULUS, PRIVATE_EXPONENT);
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
// 模长
int key_len = privateKey.getModulus().bitLength() / 8;
byte[] bytes = data.getBytes();
byte[] bcd = ASCII_To_BCD(bytes, bytes.length);
// 如果密文长度大于模长则要分组解密
String ming = "";
byte[][] arrays = splitArray(bcd, key_len);
for (byte[] arr : arrays) {
ming += new String(cipher.doFinal(arr));
}
return ming;
}
/**
*
* @throws NoSuchAlgorithmException
*/
public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException {
HashMap<String, Object> map = new HashMap<String, Object>();
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSA_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
map.put("public", publicKey);
map.put("private", privateKey);
return map;
}
/**
* 使RSA
* RSA/None/PKCS1PaddingJDKAndroidRSA
* /None/NoPadding
* @param modulus
* @param exponent
* @return
*/
public static RSAPublicKey getPublicKey(String modulus, String exponent) {
try {
BigInteger b1 = new BigInteger(modulus);
BigInteger b2 = new BigInteger(exponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 使RSA
* RSA/None/PKCS1PaddingJDKAndroidRSA
* /None/NoPadding
*
* @param modulus
* @param exponent
* @return
*/
public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
try {
BigInteger b1 = new BigInteger(modulus);
BigInteger b2 = new BigInteger(exponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
*
*
* @param data
* @param publicKey
* @return
* @throws Exception
*/
public static String encryptByPublicKey(String data, RSAPublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 模长
int key_len = publicKey.getModulus().bitLength() / 8;
// 加密数据长度 <= 模长-11
String[] datas = splitString(data, key_len - 11);
String mi = "";
// 如果明文长度大于模长-11则要分组加密
for (String s : datas) {
mi += bcd2Str(cipher.doFinal(s.getBytes()));
}
return mi;
}
/**
*
*
* @param data
* @param privateKey
* @return
* @throws Exception
*/
public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
// 模长
int key_len = privateKey.getModulus().bitLength() / 8;
byte[] bytes = data.getBytes();
byte[] bcd = ASCII_To_BCD(bytes, bytes.length);
// 如果密文长度大于模长则要分组解密
String ming = "";
byte[][] arrays = splitArray(bcd, key_len);
for (byte[] arr : arrays) {
ming += new String(cipher.doFinal(arr));
}
return ming;
}
/**
* ASCIIBCD
*/
public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {
byte[] bcd = new byte[asc_len / 2];
int j = 0;
for (int i = 0; i < (asc_len + 1) / 2; i++) {
bcd[i] = asc_to_bcd(ascii[j++]);
bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));
}
return bcd;
}
public static byte asc_to_bcd(byte asc) {
byte bcd;
if ((asc >= '0') && (asc <= '9'))
bcd = (byte) (asc - '0');
else if ((asc >= 'A') && (asc <= 'F'))
bcd = (byte) (asc - 'A' + 10);
else if ((asc >= 'a') && (asc <= 'f'))
bcd = (byte) (asc - 'a' + 10);
else
bcd = (byte) (asc - 48);
return bcd;
}
/**
* BCD
*/
public static String bcd2Str(byte[] bytes) {
char temp[] = new char[bytes.length * 2], val;
for (int i = 0; i < bytes.length; i++) {
val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
val = (char) (bytes[i] & 0x0f);
temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
}
return new String(temp);
}
/**
*
*/
public static String[] splitString(String string, int len) {
int x = string.length() / len;
int y = string.length() % len;
int z = 0;
if (y != 0) {
z = 1;
}
String[] strings = new String[x + z];
String str = "";
for (int i = 0; i < x + z; i++) {
if (i == x + z - 1 && y != 0) {
str = string.substring(i * len, i * len + y);
} else {
str = string.substring(i * len, i * len + len);
}
strings[i] = str;
}
return strings;
}
/**
*
*/
public static byte[][] splitArray(byte[] data, int len) {
int x = data.length / len;
int y = data.length % len;
int z = 0;
if (y != 0) {
z = 1;
}
byte[][] arrays = new byte[x + z][];
byte[] arr;
for (int i = 0; i < x + z; i++) {
arr = new byte[len];
if (i == x + z - 1 && y != 0) {
System.arraycopy(data, i * len, arr, 0, y);
} else {
System.arraycopy(data, i * len, arr, 0, len);
}
arrays[i] = arr;
}
return arrays;
}
public static void main(String[] args) throws Exception {
/*HashMap<String, Object> map = RSAUtil.getKeys();
//生成公钥和私钥
RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");
//模
String MODULUS = publicKey.getModulus().toString();
System.err.println("MODULUS:" + MODULUS);
//公钥指数
String PUBLIC_EXPONENT = publicKey.getPublicExponent().toString();
System.err.println("PUBLIC_EXPONENT:" + PUBLIC_EXPONENT);
//私钥指数
String PRIVATE_EXPONENT = privateKey.getPrivateExponent().toString();
System.err.println("PRIVATE_EXPONENT:" + PRIVATE_EXPONENT);
//明文
String ming = "Hello World";
//使用模和指数生成公钥和私钥
RSAPublicKey pubKey = RSAUtil.getPublicKey(MODULUS, PUBLIC_EXPONENT);
RSAPrivateKey priKey = RSAUtil.getPrivateKey(MODULUS, PRIVATE_EXPONENT);
//加密后的密文
String mi = RSAUtil.encryptByPublicKey(ming, pubKey);
System.err.println("加密后密文:"+mi);
//解密后的明文
ming = RSAUtil.decryptByPrivateKey(mi, priKey);
System.err.println("解密后明文" + ming);
String jiami = encryptByPublicKey("Hello World");
System.out.println(jiami);
System.out.println(decryptByPrivateKey("03825E2354E22EE0E09E8C9048CD41D649ECA5935C558E0278CC4FD9DE526404ACF0F1C7ED6D5B4A9BC456D0F6BFD0C5630DB59202B4295E4ADD1411441CEFE2FAE9A34B1A0D7AAF23DE0584DE6C2D2699E6C21F38D894105C0CC9DCD7C855153CC7C3D8B0375889AED2C7FD9E3706092A0383D0D35D98558A9B5353A9DA2FA9E9CAD5174BBDA1CDD14A8AF9FFD19150D1E286C8EFF47CAA96F549E66A0251C479239A5EC8677CB00D3C6878F488358EEECF10193478F5E69AF9987627C0BF13A7B2A79C207AD4289455DF7E7B8BD00A2CF8A9AB43CA78476DC7680D5C823060C58C86E89BC865DB1D9E9D5A2A6485C3500A43E8C21833E4487DB3E97DB39374"));
*/
}
}

@ -0,0 +1,16 @@
package com.springcloud.commons;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CommonsJarApplicationTests {
@Test
public void contextLoads() {
}
}

@ -0,0 +1,29 @@
HELP.md
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
/build/
### VS Code ###
.vscode/

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springcloud.configserver</groupId>
<artifactId>config-server-git</artifactId>
<version>v1.0.0</version>
<name>config-server-git</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,16 @@
package com.springcloud.configserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.ConfigServerApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigServerGitApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerGitApplication.class, args);
}
}

@ -0,0 +1,29 @@
package com.springcloud.configserver.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @name: PropertyController
* @desc: TODO
* @author: gxing
* @date: 2019-04-10 18:27
**/
@RestController
@RequestMapping("/property")
public class PropertyController {
@Autowired
private Environment environment;
@GetMapping("/url")
public String getUrl(){
String gitUrl = environment.getProperty("spring.cloud.config.server.git.uri");
return gitUrl;
}
}

@ -0,0 +1,26 @@
# 端口
server.port=9010
#spring.profiles.active=git
# 应用名
spring.application.name=config-repo
# 注册到 Eureka
eureka.client.service-url.defaultZone=http://admin:123456@eureka.master.com:8761/eureka,http://admin:123456@eureka.slave.com:8762/eureka
# Git URI 使用占位符
spring.cloud.config.server.git.uri=https://github.com/gxing19/config-repo
#spring.cloud.config.server.git.uri=https://github.com/gxing19/${spring.application.name}
# 设置 HTTP 连接超时时长, 单位:秒
spring.cloud.config.server.git.timeout=10
# foce-pull 默认 false
spring.cloud.config.server.git.force-pull=true
# 删除本地未跟踪的库
spring.cloud.config.server.git.delete-untracked-branches=true
# Rabbitmq
spring.rabbitmq.host=10.0.3.6
spring.rabbitmq.port=5672
spring.rabbitmq.username=configServer
spring.rabbitmq.password=123456
management.endpoints.web.exposure.include=bus-refresh,bus-env

@ -0,0 +1,77 @@
#端口
server.port=9010
#应用名
#spring.application.name=configServer
spring.application.name=config-repo
#eureka 注册中心地址
#eureka.client.service-url.defaultZone=http://eureka.master.com:8761/eureka,http://eureka.slave.com:8762/eureka
eureka.client.service-url.defaultZone=http://admin:123456@eureka.master.com:8761/eureka,http://admin:123456@eureka.slave.com:8762/eureka
# 配置管理仓库
#spring.cloud.config.server.git.uri=https://github.com/spring-cloud-samples/config-repo
# Git URI 使用占位符
spring.cloud.config.server.git.uri=https://github.com/spring-cloud-samples/${spring.application.name}
# 模式匹配
#spring.cloud.config.server.git.uri=https://github.com/spring-cloud-samples/config-repo
#spring.cloud.config.server.git.repos.simple=https://github.com/simple/config-repo
#spring.cloud.config.server.git.repos.special.pattern=special*/dev*,*special*/dev*
#spring.cloud.config.server.git.repos.special.uri=https://github.com/special/config-repo
#spring.cloud.config.server.git.repos.local.pattern=local*
#spring.cloud.config.server.git.repos.local.uri=file:/home/configsvc/config-repo
# 使用数组匹配多个配置文件
#spring.cloud.config.server.git.uri=https://github.com/spring-cloud-samples/config-repo
#spring.cloud.config.server.git.repos.development.pattern[0]=*/development
#spring.cloud.config.server.git.repos.development.pattern[1]=*/staging
#spring.cloud.config.server.git.repos.development.uri=https://github.com/development/config-repo
#spring.cloud.config.server.git.repos.staging.pattern[0]=*/qa
#spring.cloud.config.server.git.repos.staging.pattern[1]=*/production
#spring.cloud.config.server.git.repos.staging.uri=https://github.com/staging/config-repo
# 指定首次请求是否克隆存储库
#spring.cloud.config.server.git.uri=https://git/common/config-repo.git
#spring.cloud.config.server.git.repos.team-a.pattern=team-a-*
#spring.cloud.config.server.git.repos.team-a.clone-on-start=true
#spring.cloud.config.server.git.repos.team-a.uri=http://git/team-a/config-repo.git
#spring.cloud.config.server.git.repos.team-b.pattern=team-b-*
#spring.cloud.config.server.git.repos.team-b.clone-on-start=false
#spring.cloud.config.server.git.repos.team-b.uri=http://git/team-b/config-repo.git
#spring.cloud.config.server.git.repos.team-c.pattern=team-c-*
#spring.cloud.config.server.git.repos.team-c.uri=http://git/team-a/config-repo.git
# Git 认证
#spring.cloud.config.server.git.uri=https://github.com/spring-cloud-samples/config-repo
#spring.cloud.config.server.git.username=trolley
#spring.cloud.config.server.git.password=strongPassword
#spring.cloud.config.server.git.force-pull=true
#spring.cloud.config.server.git.delete-untracked-branches=true
#spring.cloud.config.server.git.refresh-rate=5
# 配置存储在子目录中
#spring.cloud.config.server.git.search-paths=foo,bar*
# 禁用配置服务器对 Git服务器的SSL证书的验证
spring.cloud.config.server.git.skip-ssl-validation=true
# 设置 HTTP 连接超时时长, 单位:秒
spring.cloud.config.server.git.timeout=10
#spring.config.name=configServer
#logging.level.root=debug
# 配置属性覆盖
#spring.cloud.config.server.overrides.foo=bar
# 健康指标器
#spring.cloud.config.server.health.repositories.myservice.label=mylabel
#spring.cloud.config.server.health.repositories.myservice-dev.name=myservice
#spring.cloud.config.server.health.repositories.myservice-dev.profiles=development
# Spring Security 账号密码
#spring.security.user.name=admin
spring.security.user.password=strong_password

@ -0,0 +1,16 @@
package com.springcloud.configserver;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ConfigServerApplicationTests {
@Test
public void contextLoads() {
}
}

@ -0,0 +1,29 @@
HELP.md
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
/build/
### VS Code ###
.vscode/

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save