springSpringFramework学习

【Springboot之切面编程】注解实现敏感字段加解密

2018-12-27  本文已影响96人  zetting

当你的项目如果不允许明文存储敏感数据(例如身份证号、银行卡号,手机号等),那么每次存之前都要先将相关敏感字段数据加密、读取出来都要将相应敏感字段的数据解密,这种方式低效、代码臃肿,容易出错。固本文推荐用Aop切面,通过简单注解即可完成加解密工作。用法大致如下:

 @Override
    @EncryptMethod//相应方法加上 @EncryptMethod
    public TestResponse testDecrypt(TestRequest request) {
     ....  
     }

public class TestRequest {
    private String name;
    private String sex;
    @EncryptField
    private String bankCardNo;//敏感字段加@EncryptField,则入参会自动加密该字段
   ....
}

public class TestResponse{
    private String name;
    private String sex;
    @EncryptField
    private String bankCardNo;//敏感字段加@EncryptField,则出参会自动解密该字段
   ....
}

目录

1、自定义敏感字段加解密切面

1.1 定义方法注解@EncryptMethod

package com.zetting.aop;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.lang.annotation.*;

/**
 *  安全字段注解
 * 加在需要加密/解密的方法上
 * 实现自动加密解密
 *
 * @author: zetting
 * @date:2018/12/27
 */
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface EncryptMethod {
}

1.2 定义字段注解@EncryptField

package com.zetting.aop;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.lang.annotation.*;

/**
 * 安全字段注解
 * 加在需要加密/解密的字段上
 *
 * @author: zetting
 * @date:2018/12/27
 */
@Documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface EncryptField {
}

1.3 新增配置和加密工具

image.png

加解密工具

package com.zetting.util;

import org.springframework.util.Base64Utils;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


/**
 * Ase加密
 *
 * @Author: zetting
 * @Date: 2018-05-23 22:13
 */
public class AseUtil {

    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) {
            Logger.getLogger(AseUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        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) {
            Logger.getLogger(AseUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        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) {
            Logger.getLogger(AseUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}

1.4 定义AOP核心处理类EncryptFieldAop

package com.zetting.aop;

import com.zetting.util.AseUtil;
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.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.lang.reflect.Method;
import java.util.Objects;

/**
 * 安全字段加密解密切面
 *
 * @author: zetting
 * @date:2018/12/27
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@Aspect
@Component
public class EncryptFieldAop {
    Logger log = LoggerFactory.getLogger(this.getClass());
    @Value("${secretkey}")
    private String secretKey;

    @Pointcut("@annotation(com.zetting.aop.EncryptMethod)")
    public void annotationPointCut() {
    }

    @Around("annotationPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        Object responseObj = null;
        try {
            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 = AseUtil.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 = AseUtil.decrypt(encryptValue, secretKey);
                field.set(responseObj, plaintextValue);
            }
        }
        return responseObj;
    }
}

2、使用该切面

package com.zetting.service.impl;

import com.zetting.aop.EncryptMethod;
import com.zetting.dto.DecryptRequest;
import com.zetting.dto.DecryptResponse;
import com.zetting.dto.EncryptRequest;
import com.zetting.dto.EncryptResponse;
import com.zetting.service.TestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * 测试服务实现类
 *
 * @author: zetting
 * @date:2018/12/27
 */
@Service
public class TestServiceImpl implements TestService {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @EncryptMethod
    @Override
    public EncryptResponse testEncrypt(EncryptRequest request) {
        logger.info("testEncrypt 业务逻辑入参 request:{}", request.toString());
        return null;
    }

    @Override
    @EncryptMethod
    public DecryptResponse testDecrypt(DecryptRequest request) {
        logger.info("testDecrypt  业务逻辑入参 request:{}", request.toString());

        DecryptResponse response = new DecryptResponse();
        BeanUtils.copyProperties(request, response);
        return response;
    }
}

测试加密入参

package com.zetting.dto;


import com.zetting.aop.EncryptField;

/**
 * 测试加密入参
 *
 * @author: zetting
 * @date:2018/12/27
 */
public class EncryptRequest {
    /**
     * 姓名
     */
    private String name;

    /**
     * 性别
     */
    private String sex;

    /**
     * 银行卡号
     */
    @EncryptField
    private String bankCardNo;

    /**
     * 身份证号
     */
    @EncryptField
    private String idCard;


    @Override
    public String toString() {
        if (this == null) {
            return null;
        }
        return String.format("{\n" +
                "    \"name\": \"%s\",\n" +
                "    \"sex\": \"%s\",\n" +
                "    \"bankCardNo\": \"%s\",\n" +
                "    \"idCard\": \"%s\"\n" +
                "}", this.name, this.sex, this.bankCardNo, this.idCard);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getBankCardNo() {
        return bankCardNo;
    }

    public void setBankCardNo(String bankCardNo) {
        this.bankCardNo = bankCardNo;
    }

    public String getIdCard() {
        return idCard;
    }

    public void setIdCard(String idCard) {
        this.idCard = idCard;
    }
}

3、演示

入参自动解密:


image.png

出差自动解密:


image.png

gitee源码地址:https://gitee.com/Zetting/my-gather/tree/master/springboot-aop-encrypt-field

上一篇下一篇

猜你喜欢

热点阅读