91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Springboot如何使用filter對response內容進行加密方式

發布時間:2022-03-15 12:44:16 來源:億速云 閱讀:487 作者:小新 欄目:開發技術

這篇文章主要介紹Springboot如何使用filter對response內容進行加密方式,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

使用filter對response內容進行加密

編寫加密類(AES)

/**
 * aes加密解密
 */
public class AesEncryptUtils {
    //參數分別代表 算法名稱/加密模式/數據填充方式
    private static String algorithmstr = "AES/ECB/PKCS5Padding";
    public static String getAlgorithmstr() {
        return algorithmstr;
    }
    /**
     * 加密
     * @param content 加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(algorithmstr);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        byte[] b = cipher.doFinal(content.getBytes("utf-8"));
        return Base64.encodeBase64String(b);
    }
    /**
     * 解密
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(algorithmstr);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }
    public static void main(String[] args) throws Exception{
        String str  = "pp2bQLjabobRWp2T5Ro5/GlqWCigmkwHYnrOK11VZkTkIA2hSwnEi1sijfTV6Ozd/";
        System.out.println(decrypt(str,"f8db034bda44rtkb"));
    }
}

編寫Filter類

/**
 * 過濾器攔截請求,實現加密解密功能
 *
 * @Component 將此Filter交給Spring容器管理
 * @WebFilter 通過WebFilter進行Filter聲明,這樣容器在進行部署的時候就會處理該Filter
 *
 */
@Component
public class EncryptFilter implements Filter {
    Logger log = LoggerFactory.getLogger(this.getClass());
    @Value("${admin.encrypt.excludeUrl}")
    private String ignoreStr;
    private String[] ignoreArr;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
    }
    /**
     * 有錯誤相應返回-44
     *
     * @param response
     * @throws IOException
     */
    private void getFailResponse(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        out = response.getWriter();
//        out.write("{\n" +
//                "    \"status\":"+ Constant.ENCRYPT_FAIL +",\n" +
//                "    \"message\": null,\n" +
//                "    \"data\": []\n" +
//                "}");
        //加密后的錯誤消息
        out.write("+D+JO8tuwkrNbxnTTLdqStifmQceT+LlYETnIG/JZKrbAn+gIiqIp3VbzBV1y6R8B7aY53VM2xHa7cY3Osbnqw==");
        out.flush();
        out.close();
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        if(ignoreArr==null){
            ignoreArr = ignoreStr.split(",");
        }
        HttpServletRequest HttpRequest=(HttpServletRequest)request;
        HttpServletResponse HttpResponse=(HttpServletResponse)response;
        boolean flag=isIgnore(HttpRequest,ignoreArr);
        if(flag) {
            try {
                chain.doFilter(HttpRequest, HttpResponse);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }else{
            try{
                //響應處理  包裝響應對象 res 并緩存響應數據
                ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);
                //執行業務邏輯 交給下一個過濾器或servlet處理
                chain.doFilter(request, responseWrapper);
                byte[] resData = responseWrapper.getResponseData();
                //設置響應內容格式,防止解析響應內容時出錯
//            responseWrapper.setContentType("text/plain;charset=UTF-8");
                //加密響應報文并響應
                String encryptBASE64 = AesEncryptUtils.encrypt(new String(resData),Constant.ENCRYPT_STR);
                PrintWriter out = response.getWriter();
                out.print(encryptBASE64);
                out.flush();
                out.close();
            }catch(Exception e){
                try {
                    getFailResponse((HttpServletResponse)response);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                e.printStackTrace();
            }
        }
}
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }
    /**
     * 哪些路徑不處理
     * @param request
     * @param strArr
     * @return
     */
    public boolean isIgnore(HttpServletRequest request,String[] strArr) {
        String path=request.getRequestURI();
        for(String ignore:strArr) {
            if(path.contains(ignore)) {
                return true;
            }
        }
        return false;
    }
}

下圖是對應的application.properties中的配置

Springboot如何使用filter對response內容進行加密方式

其中用到了兩個工具類

RequestWrapper

/**
 * @Description: 請求包裝類
 * @Date: 2020/5/26 16:29
 */
public class RequestWrapper extends HttpServletRequestWrapper {
    private String requestBody = null;
    //請求體
    private HttpServletRequest req = null;
    //    private final byte[] body;//保存流的字節數組
    private final Map<String, String> reqHeaders=new HashMap<>();
    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        this.req = request;
//        this.reqHeaders = new HashMap<String, String>();
//        String sessionStream = getRequestBodyStr(request);//讀取流中的參數
//        body = sessionStream.getBytes(Charset.forName("UTF-8"));
    }
    public RequestWrapper(HttpServletRequest request, String requestBody) {
        super(request);
        this.requestBody = requestBody;
        this.req = request;
//        this.reqHeaders = request.get;
    }
    /**
     * @Description: 獲取請求body
     * @Date: 2020/5/26 10:31
     * @Param: [request]
     * @Return: java.lang.String
     */
    public String getRequestBodyStr(final ServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = cloneInputStream(request.getInputStream());
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (reader != null) {
                reader.close();
            }
        }
        return sb.toString();
    }
    /**
     * @Description: 復制輸入流
     * @Param: [inputStream]
     * @Return: java.io.InputStream
     */
    public InputStream cloneInputStream(ServletInputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) > -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        byteArrayOutputStream.flush();
        InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        return byteArrayInputStream;
    }
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody.getBytes(req.getCharacterEncoding()));
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }
            @Override
            public void setReadListener(ReadListener readListener) {
            }
            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }
    /**
     * 添加header的名稱和值
     *
     * @param name
     * @param value
     */
    public void addHeader(String name, String value) {
        reqHeaders.put(name, value);
    }
    @Override
    public String getHeader(String name) {
//        log.info("getHeader --->{}", name);
        String headerValue = super.getHeader(name);
        if (reqHeaders.containsKey(name)) {
            headerValue = reqHeaders.get(name);
        }
        return headerValue;
    }
    /**
     * 得到headers的名稱
     */
    @Override
    public Enumeration<String> getHeaderNames() {
        List<String> names = Collections.list(super.getHeaderNames());
        for (String name : reqHeaders.keySet()) {
            names.add(name);
        }
        return Collections.enumeration(names);
    }
    @Override
    public Enumeration<String> getHeaders(String name) {
//        log.info("getHeaders name --->>>>>>{}", name);
        List<String> values = Collections.list(super.getHeaders(name));
//        log.info("getHeaders value --->>>>>>{}", values);
        if (reqHeaders.containsKey(name)) {
            values = Arrays.asList(reqHeaders.get(name));
        }
        return Collections.enumeration(values);
    }
}

ResponseWrapper

/**
 * @Description: 響應包裝類
 * @Date: 2020/5/26 16:29
 */
public class ResponseWrapper extends HttpServletResponseWrapper {
    private ByteArrayOutputStream buffer = null;
    private ServletOutputStream out = null;
    private PrintWriter writer = null;
    public ResponseWrapper(HttpServletResponse response) throws IOException {
        super(response);
        buffer = new ByteArrayOutputStream();// 真正存儲數據的流
        out = new WapperedOutputStream(buffer);
        writer = new PrintWriter(new OutputStreamWriter(buffer,this.getCharacterEncoding()));
    }
    /** 重載父類獲取outputstream的方法 */
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return out;
    }
    /** 重載父類獲取writer的方法 */
    @Override
    public PrintWriter getWriter() throws UnsupportedEncodingException {
        return writer;
    }
    /** 重載父類獲取flushBuffer的方法 */
    @Override
    public void flushBuffer() throws IOException {
        if (out != null) {
            out.flush();
        }
        if (writer != null) {
            writer.flush();
        }
    }
    @Override
    public void reset() {
        buffer.reset();
    }
    /** 將out、writer中的數據強制輸出到WapperedResponse的buffer里面,否則取不到數據 */
    public byte[] getResponseData() throws IOException {
        flushBuffer();
        return buffer.toByteArray();
    }
    /** 內部類,對ServletOutputStream進行包裝 */
    private class WapperedOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream bos = null;
        public WapperedOutputStream(ByteArrayOutputStream stream)
                throws IOException {
            bos = stream;
        }
        @Override
        public void write(int b) throws IOException {
            bos.write(b);
        }
        @Override
        public void write(byte[] b) throws IOException {
            bos.write(b, 0, b.length);
        }
        @Override
        public boolean isReady() {
            return false;
        }
        @Override
        public void setWriteListener(WriteListener writeListener) {
        }
    }
}

寫配置類

@Configuration
public class WebConfiguration {
    @Autowired
    private EncryptFilter encryptFilter;
    @Bean
    public FilterRegistrationBean registFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(encryptFilter);
        registration.addUrlPatterns("/*");
        registration.setName("EncryptFilter");
        registration.setOrder(1);
//        registration.setEnabled(false);
        return registration;
    }
    
    //做跨域處理,跟這個filter沒關系
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowCredentials(true)
                        .allowedMethods("*")
                        .allowedHeaders("*")
                        .maxAge(3600);
            }
        };
    }
}

Springboot數據加密傳輸

創建加解密注解注解

對于攔截路徑上全部采用數據加解密處理,如果有部分接口不需要加解密處理的話,在方法上或者類上加上此注解即可不做加解密處理

package com.hars.common.infrastructure.validation.security;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 加解密注解
 *
 * @author Huangbigao
 * @date 2020/8/29 11:02
 */
@Documented
@Target({ElementType.METHOD, ElementType.TYPE,})
@Retention(RetentionPolicy.RUNTIME)
public @interface CryptoDecryptionSecurity {
    /**
     * 是否加解密,默認加解密
     *
     * @return
     */
    boolean cryptoDecryption() default true;
    /**
     * 是否進行request 解密,默認進行解密
     *
     * @return
     */
    boolean requestDecryption() default true;
    /**
     * 是否對輸出結果進行加密,默認進行加密
     *
     * @return
     */
    boolean responseCrypto() default true;
}

ps:注解使用

 	@CryptoDecryptionSecurity(responseCrypto = false)
    @ApiOperation(value = "微信公眾號驗證業務處理接口")
    @GetMapping(value = "/handle/{appid}", produces = "text/plain;charset=utf-8")
    public String authHandle(@PathVariable String appid,
                             @RequestParam(name = "signature", required = false) String signature,
                             @RequestParam(name = "timestamp", required = false) String timestamp,
                             @RequestParam(name = "nonce", required = false) String nonce,
                             @RequestParam(name = "echostr", required = false) String echostr,
                             HttpServletRequest request) {
        return weChatMpService.authHandle(appid, signature, timestamp, nonce, echostr, request);
    }

創建request解密類

package com.hars.common.infrastructure.utils.filter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hars.common.infrastructure.utils.aes.AesUtil;
import com.hars.common.infrastructure.utils.http.HttpContextUtil;
import com.hars.common.infrastructure.utils.string.StringUtil;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.springframework.util.Assert;
/**
 * @author Huangbigao
 * @date 2020/8/29 10:12
 */
public class DecryptionRequestUtil extends HttpServletRequestWrapper {
    private static final String APPLICATION_JSON = "application/json";
    /**
     * 所有參數的Map集合
     */
    private Map<String, String[]> parameterMap;
    /**
     * 輸入流
     */
    private InputStream inputStream;
    private final boolean valueValid = true;
    public DecryptionRequestUtil(HttpServletRequest request, String password) {
        super(request);
        String encrypt;
        String contentType = request.getHeader("Content-Type");
        if (contentType != null && contentType.contains(APPLICATION_JSON)) {
            //json
            String bodyStr = HttpContextUtil.getBodyString(request);
            if (StringUtil.isBlank(bodyStr)){
                return;
            }
            encrypt = (String) JSON.parseObject(bodyStr).get("encrypt");
        } else {
            // url
            encrypt = request.getParameter("encrypt");
        }
        String jsonData = AesUtil.decrypt(encrypt, password);
        if (StringUtil.isBlank(jsonData)){
            return;
        }
        if (contentType != null && contentType.contains(APPLICATION_JSON)) {
            if (this.inputStream == null) {
                this.inputStream = new DecryptionInputStream(new ByteArrayInputStream(jsonData.getBytes()));
            }
        }
        parameterMap = buildParams(jsonData);
    }
    private Map<String, String[]> buildParams(String src) {
        Map<String, String[]> map = new HashMap<>();
        Map<String, String> params = JSONObject.parseObject(src, new TypeReference<Map<String, String>>() {
        });
        for (String key : params.keySet()) {
            map.put(key, new String[]{params.get(key)});
        }
        return map;
    }
    @Override
    public String getParameter(String name) {
        String[] values = getParameterMap().get(name);
        if (valueValid){
            if (values != null) {
                return (values.length > 0 ? values[0] : null);
            }
            return super.getParameter(name);
        }else {
            return (values.length > 0 ? values[0] : null);
        }
    }
    @Override
    public String[] getParameterValues(String name) {
        String[] values = getParameterMap().get(name);
        if (valueValid){
            if (values != null) {
                return values;
            }
            return super.getParameterValues(name);
        }else {
            return values;
        }
    }
    @Override
    public Enumeration<String> getParameterNames() {
        Map<String, String[]> multipartParameters = getParameterMap();
        if (valueValid){
            if (multipartParameters.isEmpty()) {
                return super.getParameterNames();
            }
        }else {
            if (multipartParameters.isEmpty()) {
                return null;
            }
        }
        Set<String> paramNames = new LinkedHashSet<>();
        Enumeration<String> paramEnum = super.getParameterNames();
        while (paramEnum.hasMoreElements()) {
            paramNames.add(paramEnum.nextElement());
        }
        paramNames.addAll(multipartParameters.keySet());
        return Collections.enumeration(paramNames);
    }
    @Override
    public Map<String, String[]> getParameterMap() {
        if (valueValid){
            return parameterMap == null ? super.getParameterMap() : parameterMap;
        }else {
            return parameterMap == null ? new HashMap<>() : parameterMap;
        }
    }
    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (valueValid){
            return this.inputStream == null ? super.getInputStream() : (ServletInputStream) this.inputStream;
        }else {
            return this.inputStream == null ? null : (ServletInputStream) this.inputStream;
        }
    }
    /**
     * 自定義ServletInputStream
     */
    private class DecryptionInputStream extends ServletInputStream {
        private final InputStream sourceStream;
        /**
         * Create a DelegatingServletInputStream for the given source stream.
         *
         * @param sourceStream the source stream (never {@code null})
         */
        public DecryptionInputStream(InputStream sourceStream) {
            Assert.notNull(sourceStream, "Source InputStream must not be null");
            this.sourceStream = sourceStream;
        }
        @Override
        public int read() throws IOException {
            return this.sourceStream.read();
        }
        @Override
        public void close() throws IOException {
            super.close();
            this.sourceStream.close();
        }
        @Override
        public boolean isFinished() {
            return false;
        }
        @Override
        public boolean isReady() {
            return false;
        }
        @Override
        public void setReadListener(ReadListener readListener) {
        }
    }
}

創建response加密類

package com.hars.common.infrastructure.utils.filter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
 * @author Huangbigao
 * @date 2020/8/29 13:11
 */
public class ResponseWrapperUtil extends HttpServletResponseWrapper {
    private ByteArrayOutputStream buffer;
    private ServletOutputStream out;
    public ResponseWrapperUtil(HttpServletResponse httpServletResponse) {
        super(httpServletResponse);
        buffer = new ByteArrayOutputStream();
        out = new WrapperOutputStream(buffer);
    }
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return out;
    }
    @Override
    public void flushBuffer() throws IOException {
        if (out != null) {
            out.flush();
        }
    }
    public byte[] getContent() throws IOException {
        flushBuffer();
        return buffer.toByteArray();
    }
    private static class WrapperOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream bos;
        WrapperOutputStream(ByteArrayOutputStream bos) {
            this.bos = bos;
        }
        @Override
        public void write(int b)
                throws IOException {
            bos.write(b);
        }
        @Override
        public boolean isReady() {
            // TODO Auto-generated method stub
            return false;
        }
        @Override
        public void setWriteListener(WriteListener arg0) {
            // TODO Auto-generated method stub
        }
    }
}

創建AES加密工具類

package com.hars.common.infrastructure.utils.aes;
import com.hars.common.infrastructure.utils.string.StringUtil;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import lombok.extern.slf4j.Slf4j;
/**
 * AES 加解密 工具類
 *
 * @author Huangbigao
 * @date 2020/8/28 15:17
 */
@Slf4j
public class AesUtil {
    /**
     * AES解密
     *
     * @param content  密文
     * @param password 秘鑰,必須為16個字符組成
     * @return 明文
     */
    public static String decrypt(String content, String password) {
        try {
            if (StringUtil.isBlank(content) || StringUtil.isBlank(password)) {
                return null;
            }
            byte[] encryptByte = Base64.getDecoder().decode(content);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(password.getBytes(), "AES"));
            byte[] decryptBytes = cipher.doFinal(encryptByte);
            return new String(decryptBytes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
    /**
     * AES加密
     *
     * @param content  明文
     * @param password 秘鑰,必須為16個字符組成
     * @return 密文
     */
    public static String encrypt(String content, String password) {
        try {
            if (StringUtil.isBlank(content) || StringUtil.isBlank(password)) {
                return null;
            }
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(password.getBytes(), "AES"));
            byte[] encryptStr = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptStr);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

創建加解密Filter類

package com.hars.user.infrastructure.filter;
import com.alibaba.fastjson.JSON;
import com.hars.common.infrastructure.utils.aes.AesUtil;
import com.hars.common.infrastructure.utils.filter.DecryptionRequestUtil;
import com.hars.common.infrastructure.utils.filter.ResponseWrapperUtil;
import com.hars.common.infrastructure.validation.security.CryptoDecryptionSecurity;
import com.hars.result.infrastructure.advice.Response;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
/**
 * @author Huangbigao
 * @date 2020/8/28 16:26
 */
public class CryptoDecryptionFilter implements Filter {
    //方法映射集
    private List<HandlerMapping> handlerMappings;
    public CryptoDecryptionFilter(ApplicationContext applicationContext) {
        Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext,
                HandlerMapping.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.handlerMappings = new ArrayList<>(matchingBeans.values());
            AnnotationAwareOrderComparator.sort(this.handlerMappings);
        }
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //判斷方法上是否存在注解,如果不存在,默認加解密
        //類上的注解
        CryptoDecryptionSecurity classFlag = null;
        //方法上的注解
        CryptoDecryptionSecurity methodFlag = null;
        try {
            HandlerExecutionChain handlerExecutionChain = getHandler(httpServletRequest);
            Object handler = handlerExecutionChain != null ? handlerExecutionChain.getHandler() : null;
            if (handler instanceof HandlerMethod) {
                HandlerMethod method = (HandlerMethod) handler;
                classFlag = method.getBeanType().getAnnotation(CryptoDecryptionSecurity.class);
                methodFlag = method.getMethodAnnotation(CryptoDecryptionSecurity.class);
                //如果方法注解存在,且不加密,則直接返回
                if (methodFlag != null && !methodFlag.cryptoDecryption()) {
                    chain.doFilter(request, response);
                    return;
                }
                //如果類注解存在,且不加密,則直接返回
                if (classFlag != null && !classFlag.cryptoDecryption()) {
                    chain.doFilter(request, response);
                    return;
                }
            }
        } catch (Exception e) {
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(Response.error("該請求無效", 601)));
            return;
        }
        CryptoDecryptionSecurity currentFlag = null;
        if (methodFlag != null) {
            currentFlag = methodFlag;
        } else if (classFlag != null) {
            currentFlag = classFlag;
        }
        //加解密密碼
        String password = "Hbg584782648!@hb";
        ResponseWrapperUtil responseWrapper = null;
        //加解密處理
        if (currentFlag == null || (currentFlag.requestDecryption() && currentFlag.responseCrypto())) {
            ServletRequest requestWrapper = new DecryptionRequestUtil(httpServletRequest, password);
            responseWrapper = new ResponseWrapperUtil(httpServletResponse);
            chain.doFilter(requestWrapper, responseWrapper);
        } else if (currentFlag.requestDecryption() && !currentFlag.responseCrypto()) {
            ServletRequest requestWrapper = new DecryptionRequestUtil(httpServletRequest, password);
            chain.doFilter(requestWrapper, response);
        } else if (!currentFlag.requestDecryption() && currentFlag.responseCrypto()) {
            responseWrapper = new ResponseWrapperUtil(httpServletResponse);
            chain.doFilter(request, responseWrapper);
        } else {
            chain.doFilter(request, response);
        }
        if (responseWrapper != null) {
            byte[] content = responseWrapper.getContent();//獲取返回值
            //判斷是否有值
            if (content.length > 0) {
                String result = new String(content, "UTF-8");
                //加密
                String encryptStr = AesUtil.encrypt(result, password);
                //把返回值輸出到客戶端
                ServletOutputStream out = response.getOutputStream();
                out.write(encryptStr.getBytes());
                out.flush();
            }
        }
    }
    /**
     * 獲取訪問目標方法
     *
     * @param request
     * @return HandlerExecutionChain
     * @throws Exception
     */
    private HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
        if (this.handlerMappings != null) {
            for (HandlerMapping hm : this.handlerMappings) {
                HandlerExecutionChain handler = hm.getHandler(request);
                if (handler != null) {
                    return handler;
                }
            }
        }
        return null;
    }
}

定義過濾器的攔截路徑

	@Autowired
    private ApplicationContext applicationContext;
    
	/**
     * 添加加解密過濾器
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean encryptionDataFilterRegistration() {
        FilterRegistrationBean<CryptoDecryptionFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new CryptoDecryptionFilter(applicationContext));
        registration.addUrlPatterns("/*");
        registration.setName("cryptoDecryptionFilter");
        registration.setOrder(2);
        return registration;
    }

以上是“Springboot如何使用filter對response內容進行加密方式”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

翁牛特旗| 太白县| 南岸区| 襄樊市| 梅州市| 阳东县| 余江县| 沽源县| 汽车| 阳新县| 建始县| 天津市| 毕节市| 南丹县| 浑源县| 海口市| 永昌县| 岳西县| 民乐县| 吕梁市| 怀安县| 博乐市| 宣化县| 宁夏| 塔城市| 襄垣县| 长治县| 天峻县| 陆河县| 乐陵市| 阿坝| 云南省| 慈利县| 宁蒗| 万宁市| 石狮市| 双流县| 张家界市| 军事| 栾川县| 凯里市|