自定義注解實現(xiàn)解密+單個屬性解密

自定義注解+攔截器實現(xiàn)參數(shù)解密

1、首先定義自定義注解類

// 定義注解使用的位置方法和參數(shù)上,保留到運行時期
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CipherParam {

    /**
     * 入?yún)⑹欠窠饷?,默認解密
     */
    boolean inDecode() default true;
}

2、定義RequestBodyAdvice實現(xiàn)請求前的解密操作

/**
 * @Description 攔截controller層方法,根據(jù)自定義注解CipherParam配置,做入?yún)⒔饷芴幚? */
@Component
//basePackages  需要攔截的包
@ControllerAdvice(basePackages = { "com.*.*"})
public class DecodeRequestBodyAdvice implements RequestBodyAdvice {
    private static final Logger LOG = LoggerFactory.getLogger(DecodeRequestBodyAdvice.class);
    @Autowired
    private RsaUtils rsaUtils;
    @Value("")
    private String dev;
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage request, MethodParameter parameter, Type targetType,
                                  Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    /**
     * 入?yún)⒔饷?     */
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter, Type type,
                                           Class<? extends HttpMessageConverter<?>> aClass) {
        //獲取自定義注解
        CipherParam cipherParam = methodParameter.getMethodAnnotation(CipherParam.class);
        // controller方法沒配置加解密
        if (cipherParam == null) {
            return inputMessage;
        }
        if (cipherParam.inDecode() == false) {
            return inputMessage;
        }

        try {
            LOG.info("對方法 :【" + methodParameter.getMethod().getName() + "】入?yún)⑦M行解密");
            return new MyHttpInputMessage(inputMessage);
        } catch (Exception e) {
            return inputMessage;
        }
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    class MyHttpInputMessage implements HttpInputMessage {
        private HttpHeaders headers;

        private InputStream body;

        public MyHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
            this.headers = inputMessage.getHeaders();
            String data = IOUtils.toString(inputMessage.getBody(), "UTF-8");
            //使用工具類實現(xiàn)解密   --------------- rsaUtils.decrypt(data) ----------------------
            this.body = IOUtils.toInputStream(rsaUtils.decrypt(data), "UTF-8");
        }

        @Override
        public InputStream getBody() throws IOException {
            return body;
        }

        @Override
        public HttpHeaders getHeaders() {
            return headers;
        }
    }

}

加在方法上的注解

升級解密(單個屬性加解密)

@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CipherField {
    /**
     * 入?yún)⑹欠窠饷?,默認解密
     */
    boolean inDecode() default true;
    /**
     * 對象
     */
    Class<?> clazz();
    /**
     * 對象類型
     */
    BodyType bodyType() default BodyType.OBJECT;
    /**
     * 請求對象類型
     * @author FeiFei.Huang
     * @date 2022年06月14日
     */
    enum BodyType {
        /**
         * 對象
         */
        OBJECT,
        /**
         * 數(shù)據(jù)
         */
        ARRAY,
        ;
    }
}

加在字段上的注解

/**
 * 字段解密
 *
 */
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CipherField {

    /**
     * 入?yún)⑹欠窠饷?,默認解密
     */
    boolean inDecode() default true;
    /**
     * 對象 
     */
    Class<?> clazz();

    /**
     * 對象類型
     */
    BodyType bodyType() default BodyType.OBJECT;

    enum BodyType {
        /**
         * 對象 就是遍歷字段尋找有自定義注解的字段去解密--適用于幾個字段加密
         */
        OBJECT,
        /**
         * 數(shù)據(jù) 就是整個實體類加密
         */
        ARRAY,
        ;
    }
}

攔截方法

@Slf4j
@Component
@ControllerAdvice(basePackages = { "com.*.*"})
public class DecodeRequestBodyAdvice implements RequestBodyAdvice {

    @Value("${spring.profiles.active}")
    private String dev;
    @Value("${crypt.rsa.privateKey}")
    private String privateKey;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage request, MethodParameter parameter, Type targetType,
                                  Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    /**
     * 入?yún)⒔饷?     */
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter, Type type,
                                           Class<? extends HttpMessageConverter<?>> aClass) {

        CipherType cipherType = this.getCipherType(methodParameter);
        if (cipherType == null) {
            return inputMessage;
        }

        if (!this.isDecode(inputMessage)) {
            return inputMessage;
        }

        log.info("對方法 :【" + methodParameter.getMethod().getName() + "】入?yún)⑦M行解密");
        try {
            switch (cipherType) {
                case BODY:
                    return new BodyInputMessage(inputMessage, privateKey);
                case FIELD:
                    return new FieldInputMessage(inputMessage, methodParameter, privateKey);
                default:
                    return inputMessage;
            }
        } catch (Exception e) {
            log.error("接口 :【" + methodParameter.getMethod().getName() + "】入?yún)⒔饷艹霈F(xiàn)異常", e);
            return inputMessage;
        }
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    /**
     * 獲取類型
     *
     * @param methodParameter methodParameter
     * @return CipherType
     * @author FeiFei.Huang
     * @date 2022年06月14日
     */
    private CipherType getCipherType(MethodParameter methodParameter) {

        CipherParam cipherParam = methodParameter.getMethodAnnotation(CipherParam.class);
        if (cipherParam != null) {
            return CipherType.BODY;
        }

        CipherField cipherField = methodParameter.getMethodAnnotation(CipherField.class);
        if (cipherField != null) {
            return CipherType.FIELD;
        }

        return null;
    }

    /**
     * 是否需要解密
     *
     * @param inputMessage inputMessage
     * @return true=表示要解密, false=表示不需要解密
     * @author FeiFei.Huang
     * @date 2022年06月15日
     */
    private boolean isDecode(HttpInputMessage inputMessage) {

        boolean isDev = CommonConstant.DEV.equals(dev) || CommonConstant.TEST.equals(dev);
        if (!isDev) {
            return true;
        }

        HttpHeaders headers = inputMessage.getHeaders();
        List<String> inDecodes = headers.get("in_decode");
        if (!CollectionUtils.isEmpty(inDecodes)) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}


展示其中一個解密方式

package com.loan.app.intercepter.support;

import com.alibaba.fastjson.JSONObject;
import com.loan.app.intercepter.DecodeInputMessage;
import com.loan.business.utils.RsaUtils;
import com.loan.common.annotation.CipherField;
import com.loan.common.annotation.FieldEncrypt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.InputStream;
import java.lang.reflect.Field;

/**
 * 請求參數(shù)
 */
@Slf4j
public class FieldInputMessage extends DecodeInputMessage implements HttpInputMessage {

    private static final Logger LOG = LoggerFactory.getLogger(FieldInputMessage.class);

    public FieldInputMessage(HttpInputMessage inputMessage, MethodParameter methodParameter, String privateKey) throws Exception {

        super(inputMessage);

        CipherField cipherField = methodParameter.getMethodAnnotation(CipherField.class);
        String inputStream = this.getInputStream();
        LOG.info("接收入?yún)⒔饷?data:{}", inputStream);

        String decrypt = this.decodeMessage(inputStream, privateKey, cipherField);
        this.body = this.setInputStream(decrypt);
    }

    @Override
    public InputStream getBody() {
        return this.body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return this.headers;
    }

    /**
     * 解密消息
     *
     * @param inputStream 請求體
     * @param privateKey  私鑰
     * @param cipherField cipherField
     * @return 解密后的消息
     */
    private String decodeMessage(String inputStream, String privateKey, CipherField cipherField) throws Exception {

        Object objBody = null;
        if (cipherField.bodyType() == CipherField.BodyType.ARRAY) {
            objBody = JSONObject.parseArray(inputStream, cipherField.clazz());
        } else {
            objBody = JSONObject.parseObject(inputStream, cipherField.clazz());
        }

        Field[] allFields = objBody.getClass().getDeclaredFields();
        for (int i = 0; i < allFields.length; i++) {
            Field field = allFields[i];
            if (!field.isAnnotationPresent(FieldEncrypt.class)) {
                continue;
            }
            field.setAccessible(true);
            String value = field.get(objBody).toString();
            if (StringUtils.isBlank(value)) {
                continue;
            }
            String decrypt = RsaUtils.decrypt(value, privateKey);
            if (decrypt.startsWith("\"")){
                decrypt = decrypt.replaceAll("\"","");
            }
            field.set(objBody, decrypt);
        }

        return JSONObject.toJSONString(objBody);
    }
}

使用演示

//注解默認是對字段解密
@CipherField(clazz = H5RegisterDTO.class)
@PostMapping("/registerAndApplyV2")
public GlobalResponseEntity<String> registerAndApplyV2(@Valid @RequestBody H5RegisterDTO paramsDTO) {
  //部分解密演示  
}

實體類 只需要對手機號和身份證加密,名稱不加密

@Data
public class H5RegisterDTO {

    /**
     * 手機號
     */
    @FieldEncrypt(algorithm = EncryptAlgorithm.RSA)
    private String mobile;

    /**
    *  用戶名稱
    */
    private String userName;

    /**
    *  身份證
    */
    @FieldEncrypt(algorithm = EncryptAlgorithm.RSA)
    private String idCard;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容