AES实现接口的安全性
创始人
2024-01-31 08:23:06
0

文章目录

  • Maven项目结构图
  • 引入依赖
  • AESUtils
  • EnDecryptUtil
  • EncryptProperties
  • EncryptAutoConfiguration
  • spring.factories
  • 打成jar包,供其他项目 / 人使用
    • 打成jar 包
    • 导入 jar 包
  • 测试
    • application.yaml
    • User类
    • HelloController 测试

代码地址:
链接:https://pan.baidu.com/s/1SKKo6yMG6gQOe6G2TCuAqw
提取码:yyds

Maven项目结构图

在这里插入图片描述

引入依赖



com.github.encrypt
encrypt-spring-boot-starter
1.01.8UTF-8UTF-82.3.12.RELEASE
org.springframework.bootspring-boot-configuration-processororg.projectlomboklombokorg.springframework.bootspring-boot-starter-web

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";// 获取 cipherprivate 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 decrypt(String data, Class 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 传输会把 +号转为 空格//把 所有空格换成 +号,这是个bugboolean 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  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 {@Resourceprivate EncryptProperties encryptProperties;@Resourceprivate 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//引入enDecryptUtilprivate 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);}
}

启动项目

加密操作

在这里插入图片描述

返回的是加密后的数据

在这里插入图片描述

解密操作

参数为空 或者不正确
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

参数正确

在这里插入图片描述
在这里插入图片描述

完成

相关内容

热门资讯

德银:日元疲软是政策与资金共同... 德银最新报告指出,日元持续走弱的背后,是“政策默许”与“资本外流”共同作用的结果,短期内外汇干预的可...
ST名家汇(300506)披露... 截至2026年1月16日收盘,ST名家汇(300506)报收于4.16元,较前一交易日下跌0.72%...
衍生品交易迎政策规范,证监会对... 期货衍生品市场迎来政策规范,时隔两年多,证监会再就相关管理办法公开征求意见。 1月16日晚间,证监会...
【专家解读】2026年“两新”... 党的二十届四中全会提出,坚持扩大内需这个战略基点,坚持惠民生和促消费紧密结合,促进消费和投资、供给和...
国际观察丨“斩杀线”折射美国制... 新华社北京1月16日电 题:“斩杀线”折射美国制度弊端下的脆弱民生 新华社记者邓仙来 马倩 丛佳鑫 ...
涉及与供应商的合同纠纷房产被轮... 1月16日,金浦钛业(000545.SZ)公告称,全资子公司徐州钛白因涉及与供应商的合同纠纷,房产被...
乌政府调整宵禁政策 允许部分设... 当地时间16日,乌政府批准在宵禁期间允许购物中心、药店和加油站夜间营业,如果企业能发挥“不间断服务点...
公安部:敦促陈志犯罪集团在逃犯... 公安部今日发布《关于敦促陈志犯罪集团在逃犯罪嫌疑人投案自首的通告》。 近日,重大跨境赌诈犯罪集团头目...
出口退税取消政策影响渐显 一季... 中国有色金属工业协会硅业分会发布的数据显示,本周多晶硅N型复投料成交均价为5.92万元/吨,N型颗粒...
ST数源(000909)披露子... 截至2026年1月16日收盘,ST数源(000909)报收于5.41元,较前一交易日下跌0.55%,...