SpringBoot框架接口数据加密(base64)传输(前后分离版本)

2023-12-14 10:53:30

技术采用Filter+HttpServletRequestWrapper+HttpServletResponseWrapper+base64

1、前端加解密

? ? ? ? 1.1 vue引入开源的base64

1、下载依赖
$ npm install --save js-base64
 
2、使用方法:
import {Base64} from 'js-base64'
 
Base64.encode('hellow world'); // 编码  aGVsbG93IFdvcmxk
Base64.decode('aGVsbG93IFdvcmxk'); // 解码  hellow World

? ?1.2 在若依系统的request.js中引入base64

? ? ? ? ?1.3 修改若依系统的request.js中的request拦截器-对config.data进行加密处理

? ? ? ? ?1.4 修改若依系统的response.js中的响应拦截器-对后端传入的数据进行解密并转成json

2、后端加解密

????????2.1 新增过滤器ResponseDataFilter(名字可以随便来,但是要在注册Bean的时候,要统一)?

import com.ruoyi.common.utils.sign.Base64;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
 
public class ResponseDataFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化操作,可留空
    }
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest requests =  (HttpServletRequest) request;
        String requestBody = getRequestBody(requests);
        System.out.println(requestBody);
        //解密请求报文
        String requestBodyMw = new String(Base64.decode(requestBody), "utf-8");
        System.out.println("解密请求数据:"+requestBodyMw);
        WrapperedRequest wrapRequest = new WrapperedRequest( (HttpServletRequest) request, requestBodyMw);
        WrapperedResponse wrapResponse = new WrapperedResponse((HttpServletResponse) response);
        chain.doFilter(wrapRequest, wrapResponse);
        byte[] data = wrapResponse.getResponseData();
        System.out.println("原始返回数据: " + new String(data, "utf-8"));
        // 加密返回报文
        String responseBodyMw = Base64.encode(data);
        System.out.println("加密返回数据: " + responseBodyMw);
        response.getOutputStream().write(responseBodyMw.getBytes());
    }
 
    @Override
    public void destroy() {
        // 销毁操作,可留空
    }
 
    private String getRequestBody(HttpServletRequest req) {
        try {
            BufferedReader reader = req.getReader();
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String json = sb.toString();
            return json;
        } catch (IOException e) {
            System.out.println("请求体读取失败"+e.getMessage());
        }
        return "";
    }
 
 
}

? ? ? ? 2.2 把自己添加过滤器注册为bean(在FilterConfig.java文件写,也可以自己写配置文件)

 
  1. ?
    @Bean
        public FilterRegistrationBean requestDataFilter()
        {
            FilterRegistrationBean registration = new FilterRegistrationBean();
            //自己的过滤器叫什么名字就写上什么名字
            registration.setFilter(new ResponseDataFilter());
            registration.addUrlPatterns("/*");
            registration.setName("responseDataFilter");
            //过滤器的顺序,数字越小,越先执行,反之亦然
            registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
            return registration;
        }

    ? ? ? ? 2.3 继承HttpServletRequestWrapper和继承HttpServletResponseWrapper

     
  2. ?
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.io.UnsupportedEncodingException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.WriteListener;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpServletResponseWrapper;
    public class WrapperedResponse extends HttpServletResponseWrapper {
     
        private ByteArrayOutputStream buffer = null;
        private ServletOutputStream out = null;
        private PrintWriter writer = null;
     
        public WrapperedResponse(HttpServletResponse resp) throws IOException {
            super(resp);
            // 真正存储数据的流
            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() {
                // TODO Auto-generated method stub
                return false;
            }
     
            @Override
            public void setWriteListener(WriteListener writeListener) {
                // TODO Auto-generated method stub
     
            }
        }
    }
    import java.io.BufferedReader;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.StringReader;
    import javax.servlet.ReadListener;
    import javax.servlet.ServletInputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletRequestWrapper;
    public class WrapperedRequest extends HttpServletRequestWrapper {
     
        private String requestBody = null;
        HttpServletRequest req = null;
     
        public WrapperedRequest(HttpServletRequest request) {
            super(request);
            this.req = request;
        }
     
        public WrapperedRequest(HttpServletRequest request, String requestBody) {
            super(request);
            this.requestBody = requestBody;
            this.req = request;
        }
     
        /**
         * (non-Javadoc)
         *
         * @see javax.servlet.ServletRequestWrapper#getReader()
         */
        @Override
        public BufferedReader getReader() throws IOException {
            return new BufferedReader(new StringReader(requestBody));
        }
     
        /**
         * (non-Javadoc)
         *
         * @see javax.servlet.ServletRequestWrapper#getInputStream()
         */
        @Override
        public ServletInputStream getInputStream() throws IOException {
            return new ServletInputStream() {
                private InputStream in = new ByteArrayInputStream(
                        requestBody.getBytes(req.getCharacterEncoding()));
                @Override
                public int read() throws IOException {
                    return in.read();
                }
                @Override
                public boolean isFinished() {
                    // TODO Auto-generated method stub
                    return false;
                }
                @Override
                public boolean isReady() {
                    // TODO Auto-generated method stub
                    return false;
                }
                @Override
                public void setReadListener(ReadListener readListener) {
                    // TODO Auto-generated method stub
     
                }
            };
        }
    }

    记录技术,留下痕迹。如果有什么不合适的地方,请各位大佬留言指出,小弟改进!!!!

文章来源:https://blog.csdn.net/weixin_62108279/article/details/134987489
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。