文章目录
- Maven项目结构图
- 引入依赖
- AESUtils
- EnDecryptUtil
- EncryptProperties
- EncryptAutoConfiguration
- spring.factories
- 打成jar包,供其他项目 / 人使用
- 打成jar 包
- 导入 jar 包
- 测试
- application.yaml
- User类
- HelloController 测试
代码地址:
链接:https://pan.baidu.com/s/1SKKo6yMG6gQOe6G2TCuAqw
提取码:yyds
Maven项目结构图
引入依赖
<!-- jar 包的名称 artifactId-->
<groupId>com.github.encrypt</groupId>
<artifactId>encrypt-spring-boot-starter</artifactId>
<version>1.0</version>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.12.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
AESUtils
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtils {
private static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";
// 获取 cipher
private static Cipher getCipher(byte[] key, int model) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec (key, "AES");
Cipher cipher = Cipher.getInstance (AES_ALGORITHM);
cipher.init (model, secretKeySpec);
return cipher;
}
// AES 加密
public static String encrypt(byte[] data, byte[] key) throws Exception {
Cipher cipher = getCipher (key, Cipher.ENCRYPT_MODE);
return java.util.Base64.getEncoder ().encodeToString (cipher.doFinal (data));
}
// AES 解密
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
Cipher cipher = getCipher (key, Cipher.DECRYPT_MODE);
return cipher.doFinal (Base64.getDecoder ().decode (data));
}
}
EnDecryptUtil
http 传输会把 + 号转为 空格
把 所有空格换成 +号,这是个bug
package endecode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
@NoArgsConstructor
@Slf4j
public class EnDecryptUtil {
private String key;
private ObjectMapper om;
public EnDecryptUtil(String key, ObjectMapper om) {
this.om = om;
this.key = key;
}
public <T> T decrypt(String data, Class<T> classType) throws Exception {
log.info ("decrypt method start ");
if (key == null || key.length () != 16) {
log.error ("spring.encrypt.key 不能为空 或长度不满足16!");
return classType.newInstance ();
}
byte[] keyBytes = key.getBytes ();
if (data == null || data.length () == 0) {
log.error ("解密的数据 不能为空!");
return classType.newInstance ();
}
char[] dataChars = data.toCharArray ();
// http 传输会把 +号转为 空格
//把 所有空格换成 +号,这是个bug
boolean flag = false;
for (int i = 0; i < dataChars.length; i++) {
if (dataChars[i] == ' ') {
dataChars[i] = '+';
flag = true;
}
}
if (flag) data = new String (dataChars);
byte[] dataBytes = data.getBytes ();
log.info ("请求(原加密)参数:{}", data);
byte[] decrypt = new byte[0];
try {
decrypt = AESUtils.decrypt (dataBytes, keyBytes);
} catch (Exception e) {
log.error (" 请求参数(原加密)错误 / key 错误,无法解析", e.getMessage ());
return classType.newInstance ();
}
if (decrypt.length == 0) return null;
T rawData = null;
try {
rawData = om.readValue (decrypt, classType);
} catch (IOException e) {
log.error ("readValue转化 Exception,parameters:{}", rawData);
e.printStackTrace ();
}
log.info ("解密后的参数: {}", rawData);
log.info ("decrypt method end ");
return rawData == null ? classType.newInstance () : rawData;
}
public <T> String encrypt(T data) {
if (data == null) {
log.error ("加密的数据 不能为空!");
return "加密的数据 不能为空!";
}
log.info ("encrypt method start ");
if (key == null || key.length () != 16) {
log.error ("spring.encrypt.key 不能为空 或长度不满足16!");
return "spring.encrypt.key 不能为空 或长度不满足16!";
}
byte[] keyBytes = key.getBytes ();
String encryptData = null;
try {
encryptData = AESUtils.encrypt (om.writeValueAsBytes (data), keyBytes);
} catch (Exception e) {
log.error (" 加密失败 / key 错误,无法解析", e.getMessage ());
}
log.info ("encrypt method end ");
return encryptData == null ? "加密失败" : encryptData;
}
}
EncryptProperties
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "spring.encrypt")
public class EncryptProperties {
private final static String DEFAULT_KEY = "1Pxwol9WnHtpD5Tz";
private String key = DEFAULT_KEY;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
EncryptAutoConfiguration
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
@Configuration
@ComponentScan("endecode")
public class EncryptAutoConfiguration {
@Resource
private EncryptProperties encryptProperties;
@Resource
private ObjectMapper om;
@Bean("enDecryptUtil")
public EnDecryptUtil enDecryptUtil() {
return new EnDecryptUtil (encryptProperties.getKey (), om);
}
}
spring.factories
resources下新建目录
META-INF
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
endecode.EncryptAutoConfiguration
打成jar包,供其他项目 / 人使用
打成jar 包
起个名
选择要导出的模块
**左上角 工具栏处 **
查看jar包 所在目录
导入 jar 包
测试
application.yaml
spring:
encrypt:
key: woshigedashuaige
User类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String username;
//省略 getter/setter
}
HelloController 测试
import com.example.demo.util.Result;
import endecode.EnDecryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@Slf4j
public class HelloController {
@Resource
//引入enDecryptUtil
private EnDecryptUtil enDecryptUtil;
@GetMapping("/user")
public Result getUser() {
User user = new User (100L, "I am xiao ding");
//加密
String encryptData = enDecryptUtil.encrypt (user);
return Result.ok (encryptData);
}
@PostMapping("/user")
// http传输会把 +号转为空格
public Result addUser(String encodeMsg) throws Exception {
//解密
User user = enDecryptUtil.decrypt (encodeMsg, User.class);
if (user.getId () == null) {
user.setId (1L);
user.setUsername ("找不到");
}
return Result.ok (user);
}
}
启动项目
加密操作
返回的是
加密后的数据
解密操作
参数为空 或者不正确
参数正确
完成