AOP注解实现接口敏感字段加密
文章目录
- AOP注解实现接口敏感字段加密
- 定义方法注解@EncryptMethod
- 定义字段注解@EncryptField
- 新增加密解密工具
- 定义AOP核心处理类EncryptFieldAop
- 使用注解
项目如果不允许明文存储敏感数据(例如身份证号、银行卡号,手机号等),那么每次存之前都要先将相关敏感字段数据加密、读取出来都要将相应敏感字段的数据解密,这种方式低效、代码臃肿,容易出错。固本文推荐用Aop切面,通过简单注解即可完成加解密工作。
定义方法注解@EncryptMethod
package com.ung.controllertest.annotation;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* 安全字段注解
* 加在需要加密/解密的方法上
* 实现自动加密解密
*/
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface EncryptMethod {
}
定义字段注解@EncryptField
package com.ung.controllertest.annotation;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* 安全字段注解
* 加在需要加密/解密的字段上
*/
@Documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface EncryptField {
}
新增加密解密工具
package com.ung.controllertest.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
@Slf4j
public class AESUtil {
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
/**
* AES 加密操作
*
* @param content 待加密内容
* @param password 加密密码
* @return 返回Base64转码后的加密数据
*/
public static String encrypt(String content, String password) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化为加密模式的密码器
byte[] result = cipher.doFinal(byteContent);// 加密
return Base64Utils.encodeToString(result);
} catch (Exception ex) {
log.error(ex.getStackTrace().toString());
}
return null;
}
/**
* AES 解密操作
*
* @param content
* @param password
* @return
*/
public static String decrypt(String content, String password) {
try {
//实例化
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
//使用密钥初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
//执行操作
byte[] result = cipher.doFinal(Base64Utils.decodeFromString(content));
return new String(result, "utf-8");
} catch (Exception ex) {
log.error(ex.getStackTrace().toString());
}
return null;
}
/**
* 生成加密秘钥
*
* @return
*/
private static SecretKeySpec getSecretKey(final String password) {
//返回生成指定算法密钥生成器的 KeyGenerator 对象
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
//AES 要求密钥长度为 128
kg.init(128, new SecureRandom(password.getBytes()));
//生成一个密钥
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
} catch (NoSuchAlgorithmException ex) {
log.error(ex.getStackTrace().toString());
}
return null;
}
}
定义AOP核心处理类EncryptFieldAop
package com.ung.controllertest.aop;
import com.ung.controllertest.annotation.EncryptField;
import com.ung.controllertest.utils.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.Objects;
/**
* @Description: 安全字段加密解密切面
*/
@Order(Ordered.HIGHEST_PRECEDENCE)
@Aspect
@Component
@Slf4j
public class EncryptFieldAop {
@Value("${secretkey}")
private String secretKey;
@Pointcut("@annotation(com.ung.controllertest.annotation.EncryptMethod)")
public void annotationPointCut() {
}
@Around("annotationPointCut()")
public Object around(ProceedingJoinPoint joinPoint) {
Object responseObj = null;
try {
if (joinPoint.getArgs().length != 0) {
Object requestObj = joinPoint.getArgs()[0];
//方法进来就加密
handleEncrypt(requestObj);
}
//方法执行
responseObj = joinPoint.proceed();
//方法返回就解密
handleDecrypt(responseObj);
} catch (NoSuchMethodException e) {
e.printStackTrace();
log.error("SecureFieldAop处理出现异常{}", e);
} catch (Throwable throwable) {
throwable.printStackTrace();
log.error("SecureFieldAop处理出现异常{}", throwable);
}
return responseObj;
}
/**
* 处理加密
*
* @param requestObj
*/
private void handleEncrypt(Object requestObj) throws IllegalAccessException {
if (Objects.isNull(requestObj)) {
return;
}
//获取入参对象的字段
Field[] fields = requestObj.getClass().getDeclaredFields();
for (Field field : fields) {
//判断字段是否加了需要加密字段的注解
boolean hasSecureField = field.isAnnotationPresent(EncryptField.class);
if (hasSecureField) {
field.setAccessible(true);
String plaintextValue = (String) field.get(requestObj);
String encryptValue = AESUtil.encrypt(plaintextValue, secretKey);
field.set(requestObj, encryptValue);
}
}
}
/**
* 处理解密
*
* @param responseObj
*/
private Object handleDecrypt(Object responseObj) throws IllegalAccessException {
if (Objects.isNull(responseObj)) {
return null;
}
Field[] fields = responseObj.getClass().getDeclaredFields();
for (Field field : fields) {
boolean hasSecureField = field.isAnnotationPresent(EncryptField.class);
if (hasSecureField) {
field.setAccessible(true);
String encryptValue = (String) field.get(responseObj);
String plaintextValue = AESUtil.decrypt(encryptValue, secretKey);
field.set(responseObj, plaintextValue);
}
}
return responseObj;
}
}
配置文件设置key
server:
port: 8001
#密钥
secretkey: 123456
使用注解
实体类
package com.ung.controllertest.pojo.dto;
import com.ung.controllertest.annotation.EncryptField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class UserEncrpyDto implements Serializable {
private Long uid;
private String username;
/**
* 字段加密
*/
@EncryptField
private String password;
}
service
package com.ung.controllertest.service;
import com.ung.controllertest.pojo.dto.UserEncrpyDto;
public interface UserEncryService {
UserEncrpyDto getById(Long id);
boolean addUser(UserEncrpyDto userDto);
}
package com.ung.controllertest.service.impl;
import com.ung.controllertest.annotation.EncryptMethod;
import com.ung.controllertest.pojo.dto.UserEncrpyDto;
import com.ung.controllertest.service.UserEncryService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class UserEncryServiceImpl implements UserEncryService {
//说明:这里没有用到数据库,只是用缓存的map,也相当于数据库;
private static ConcurrentHashMap<Long, UserEncrpyDto> map = new ConcurrentHashMap<>();
//使用加密注解
@EncryptMethod
@Override
public UserEncrpyDto getById(Long id) {
if (id != null && id > 0) {
UserEncrpyDto userDto = map.get(id);
System.out.println("service 查到的:" + userDto.getPassword());
return userDto;
}
throw new RuntimeException("参数异常");
}
//使用加密注解
@EncryptMethod
@Override
public boolean addUser(UserEncrpyDto userDto) {
if (userDto != null) {
System.out.println("service传递进来的参数是:" + userDto.toString());
if (userDto.getUsername() != null) {
map.put(1L, userDto);
System.out.println("DB存的数据:" + userDto.toString());
return true;
}
}
throw new RuntimeException("参数异常");
}
}
controller
package com.ung.controllertest.controller;
import com.ung.controllertest.pojo.dto.UserEncrpyDto;
import com.ung.controllertest.service.UserEncryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
@RestController
public class UserEncryController {
private UserEncryService userService;
@Autowired
public UserEncryController(UserEncryService userService) {
this.userService = userService;
}
@GetMapping("/userEncry/getById/{id}")
public UserEncrpyDto getById(@PathVariable("id") Long id) {
UserEncrpyDto userDto = userService.getById(id);
System.out.println("controller 查到的:" + userDto.getPassword());
return userDto;
}
@PostMapping("/userEncry/addUser")
public boolean addUser(HttpServletRequest request, @RequestBody UserEncrpyDto userDto) {
System.out.println("controller 传递进来的参数是:" + userDto.toString());
return userService.addUser(userDto);
}
}
最后测试 :
先添加数据
http://localhost:8001/userEncry/addUser
{
"username": "username",
"password": "123456"
}
可以看到结果
传入的时候加密,给数据库保存
在测试取出数据
http://localhost:8001/userEncry/getById/1
可以看到取出的数据是明文解密的
可以看到service查出来的时候是加密的数据,传递给controller就变成解密了
总结:
最终效果达到,实体类的某个字段加密,不需要我们主动操作加密解密,而是加注解来标记
代码地址 https://gitee.com/wenyi49/controller-test.git