接口返回字段加密

package com.lxkj.frame.core.converter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lxkj.frame.core.annotation.Encrypt;
import com.lxkj.frame.core.status.EnumEnabled;
import com.lxkj.frame.core.status.EnumSysConfig;
import com.lxkj.frame.core.utils.RSAUtils;
import com.lxkj.frame.core.utils.StringUtils;
import com.lxkj.sys.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestControllerAdvice
public class ResponseResultAdvice implements ResponseBodyAdvice {

    @Autowired
    private SysConfigService sysConfigService;

    @Override
    public boolean supports(MethodParameter returnType, Class> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果加密标识为无效,则不作加密处理
        List encrypt = request.getHeaders().get("encrypt");
        if(!CollectionUtils.isEmpty(encrypt) && encrypt.get(0).equalsIgnoreCase("N")){
            return body;
        }

        if(body != null && body.getClass().isAnnotationPresent(Encrypt.class)){
            //检查是否已开启加密功能
            String isEnabled = sysConfigService.selectConfigByKeyCache(EnumSysConfig.SYS_SECURITY_ENABLED.getColumn_name(), EnumSysConfig.SYS_SECURITY_ENABLED.getValue());
            if(!EnumEnabled.ENABLED.getCode().equals(isEnabled)){
                return body;
            }
            List exceptUrls = Arrays.asList(sysConfigService.selectConfigByKeyCache(EnumSysConfig.SYS_SECURITY_CC_EXCEPT_URLS.getColumn_name(), EnumSysConfig.SYS_SECURITY_CC_EXCEPT_URLS.getValue()).split(","));
            String items = sysConfigService.selectConfigByKeyCache(EnumSysConfig.SYS_SECURITY_TARGET_KEYS.getColumn_name(), EnumSysConfig.SYS_SECURITY_TARGET_KEYS.getValue());
            List matchItems = Arrays.asList(items.split(","));
            String publicKey = sysConfigService.selectConfigByKeyCache(EnumSysConfig.SYS_SECURITY_RSA_KEY_PUBLIC.getColumn_name(), EnumSysConfig.SYS_SECURITY_RSA_KEY_PUBLIC.getValue());
            //确认当前请求地址是否不使用加密
            String requestUrl = request.getURI().getPath();
            for(String url : exceptUrls){
                if(url.trim().contains(requestUrl) || requestUrl.contains(url.trim())){
                    return body;
                }
            }
            //将数据对象转化为字符串
            String data = null;
            try {
                data = JSON.toJSONString(body, SerializerFeature.WriteMapNullValue);
            }catch(Exception e){
                return body;
            }
            //同时匹配多个敏感信息关键字,如果未找到则返回原始数据
            String regexAny = "";
            for(String item : matchItems){
                if(!"".equals(regexAny)){
                    regexAny = regexAny + "|";
                }
                regexAny = regexAny + "(\"" + item.trim() + "\")";
            }
            Pattern pattern = Pattern.compile(regexAny);
            Matcher matcher = pattern.matcher(data);
            if(!matcher.find()){
                return body;
            }
            //去除重复的Key
            List noRepeatItems = new ArrayList<>();
            for(String item : matchItems){
                boolean isRepeat = false;
                for(String item2 : noRepeatItems){
                    if(item.equals(item2)){
                        isRepeat = true;
                        break;
                    }
                }
                if(!isRepeat){
                    noRepeatItems.add(item);
                }
            }
            matchItems = noRepeatItems;
            //精确匹配敏感信息关键字并加密替换
            List encryptItems = new ArrayList<>();
            for(String item : matchItems){
                String regex = "(\"" + item.trim() + "\"):\"([^\"]*)\"";
                Pattern r = Pattern.compile(regex);
                Matcher m = r.matcher(data);
                while (m.find()) {
                    if(m.groupCount() == 2) {
                        String dataAll = m.group();
                        String dataKey = m.group(1);
                        String dataValue = m.group(2);
                        if(StringUtils.isNotEmpty(dataValue)) {
                            String encrytedData = RSAUtils.encryptedDataOnJava(dataValue.replace("\"", ""), publicKey);
                            data = data.replace(dataAll, dataKey + ":\"" + encrytedData + "\"");
                            if (!encryptItems.contains(item)) {
                                encryptItems.add(item);
                            }
                        }
                    }
                }
            }
            //如果存在替换则处理,则返回替换后的数据
            if(encryptItems.size() > 0) {
                //检查是否包含关键字
                if(response != null) {
                    response.getHeaders().add("encrypt", "Y");
                    response.getHeaders().add("encryptItems", StringUtils.join(encryptItems, ","));
                }
                return JSON.parseObject(data);
            }
        }
        return body;
    }

}


 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(java)