Spring Boot 接口加解密功能实现

2023-05-18 11:05:36 功能 接口 加解密

介绍

在我们日常的Java开发中,免不了和其他系统的业务交互,或者微服务之间的接口调用;如果我们想保证数据传输的安全,对接口出参加密,入参解密。但是不想写重复代码,我们可以提供一个通用starter,提供通用加密解密功能。

基础知识

hutool-crypto加密解密工具

hutool-crypto提供了很多加密解密工具,包括对称加密,非对称加密,摘要加密等等,这不做详细介绍。

request流只能读取一次的问题

问题描述

在接口调用链中,request的请求流只能调用一次,处理之后,如果之后还需要用到请求流获取数据,就会发现数据为空。

比如使用了filter或者aop在接口处理之前,获取了request中的数据,对参数进行了校验,那么之后就不能在获取request请求流了。

解决办法

继承httpservletRequestWrapper,将请求中的流copy一份,复写getInputStream和getReader方法供外部使用。每次调用后的getInputStream方法都是从复制出来的二进制数组中进行获取,这个二进制数组在对象存在期间一致存在。

使用Filter过滤器,在一开始,替换request为自己定义的可以多次读取流的request。

下面这样就实现了流的重复获取:
工具类(InputStreamHttpServletRequestWrapper):

package com.mry.springboottools.validation;
import org.apache.commons.io.IOUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class InputStreamHttpServletRequestWrapper extends HttpServletRequestWrapper {
    
    private ByteArrayOutputStream cachedBytes;
    public InputStreamHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }
    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (cachedBytes == null) {
            // 首次获取流时,将流放入 缓存输入流 中
            cacheInputStream();
        }
        // 从 缓存输入流 中获取流并返回
        return new CachedServletInputStream(cachedBytes.toByteArray());
    }
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
    
    private void cacheInputStream() throws IOException {
        // 缓存输入流以便多次读取。为了方便, 我使用 org.apache.commons IOUtils
        cachedBytes = new ByteArrayOutputStream();
        IOUtils.copy(super.getInputStream(), cachedBytes);
    }
    
    public static class CachedServletInputStream extends ServletInputStream {
        private final ByteArrayInputStream input;
        public CachedServletInputStream(byte[] buf) {
            // 从缓存的请求正文创建一个新的输入流
            input = new ByteArrayInputStream(buf);
        }
        @Override
        public boolean isFinished() {
            return false;
        }
        @Override
        public boolean isReady() {
            return false;
        }
        @Override
        public void setReadListener(ReadListener listener) {
        }
        @Override
        public int read() throws IOException {
            return input.read();
        }
    }
}

Filter过滤器(HttpServletRequestInputStreamFilter):

package com.mry.springboottools.validation;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;

@Component
@Order(HIGHEST_PRECEDENCE + 1)  // 优先级最高
public class HttpServletRequestInputStreamFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 转换为可以多次获取流的request
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        InputStreamHttpServletRequestWrapper inputStreamHttpServletRequestWrapper = new InputStreamHttpServletRequestWrapper(httpServletRequest);
        // 放行
        chain.doFilter(inputStreamHttpServletRequestWrapper, response);
    }
}

SpringBoot的参数校验validation

为了减少接口中,业务代码之前的大量冗余的参数校验代码

SpringBoot-validation提供了优雅的参数校验,入参都是实体类,在实体类字段上加上对应注解,就可以在进入方法之前,进行参数校验,如果参数错误,会抛出错误BindException,是不会进入方法的。

这种方法,必须要求在接口参数上加注解@Validated或者是@Valid

但是很多清空下,我们希望在代码中调用某个实体类的校验功能,所以需要如下工具类。

package com.mry.springboottools.validation;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class ValidationUtils {
    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
    
    public static void validate(Object object) throws CustomizeException {
        Set<ConstraintViolation<Object>> validate = VALIDATOR.validate(object);
        // 验证结果异常
        throwParamException(validate);
    }
    
    public static void validate(Object object, Class<?> ... groups) throws CustomizeException {
        Set<ConstraintViolation<Object>> validate = VALIDATOR.validate(object, groups);
        // 验证结果异常
        throwParamException(validate);
    }
    
    public static void validate(Object object, String propertyName) throws CustomizeException {
        Set<ConstraintViolation<Object>> validate = VALIDATOR.validateProperty(object, propertyName);
        // 验证结果异常
        throwParamException(validate);
    }
    
    public static void validate(Object object, String propertyName, Class<?> ... groups) throws CustomizeException {
        Set<ConstraintViolation<Object>> validate = VALIDATOR.validateProperty(object, propertyName, groups);
        // 验证结果异常
        throwParamException(validate);
    }
    
    private static void throwParamException(Set<ConstraintViolation<Object>> validate) throws CustomizeException {
        if (validate.size() > 0) {
            List<String> fieldList = new LinkedList<>();
            List<String> msgList = new LinkedList<>();
            for (ConstraintViolation<Object> next : validate) {
                fieldList.add(next.getPropertyPath().toString());
                msgList.add(next.getMessage());
            }
            throw new ParamException(fieldList, msgList);
        }
    }
}

自定义参数异常:

package com.mry.springboottools.validation;
import lombok.Getter;
import org.springframework.util.CollectionUtils;
import java.util.List;

@Getter
public class ParamException extends CustomizeException {
    private List<String> fieldList;
    private List<String> msgList;
    public ParamException(String message) {
        super(message);
    }
    public ParamException(String message, Throwable cause) {
        super(message, cause);
    }
    public ParamException(List<String> fieldList, List<String> msgList) throws CustomizeException {
        super(generatORMessage(fieldList, msgList));
        this.fieldList = fieldList;
        this.msgList = msgList;
    }
    public ParamException(List<String> fieldList, List<String> msgList, Exception ex) throws CustomizeException {
        super(generatorMessage(fieldList, msgList), ex);
        this.fieldList = fieldList;
        this.msgList = msgList;
    }
    private static String generatorMessage(List<String> fieldList, List<String> msgList) throws CustomizeException {
        if (CollectionUtils.isEmpty(fieldList) || CollectionUtils.isEmpty(msgList) || fieldList.size() != msgList.size()) {
            return "参数错误";
        }
        StringBuilder message = new StringBuilder();
        for (int i = 0; i < fieldList.size(); i++) {
            String field = fieldList.get(i);
            String msg = msgList.get(i);
            if (i == fieldList.size() - 1) {
                message.append(field).append(":").append(msg);
            } else {
                message.append(field).append(":").append(msg).append(",");
            }
        }
        return message.toString();
    }
}

自定义异常:

package com.mry.springboottools.validation;

public class CustomizeException extends Exception {
    public CustomizeException(String message, Throwable cause) {
        super(message, cause);
    }
    public CustomizeException(String message) {
        super(message);
    }
}

自定义starter

自定义starter步骤:
1.创建工厂,编写功能代码;
2.声明自动配置类,把需要对外提供的对象创建好,通过配置类统一向外暴露;
3.在resource目录下准备一个名为spring/spring.factories的文件,以org.springframework.boot.autoconfigure.EnableAutoConfiguration为key,自动配置类为value列表,进行注册;

RequestBodyAdvice和ResponseBodyAdvice

1.RequestBodyAdvice是对请求的JSON串进行处理, 一般使用环境是处理接口参数的自动解密;
2.ResponseBodyAdvice是对请求响应的json传进行处理,一般用于相应结果的加密;

功能介绍

接口数据的时候,返回的是加密之后的数据 接口入参的时候,接收的是解密之后的数据,但是在进入接口之前,加密的会自动解密,取得对应的数据。

功能细节

加密解密使用对称加密的AES算法,使用hutool-crypto模块进行实现

所有的实体类提取一个公共父类,包含属性时间戳,用于加密数据返回之后的实效性,如果超过60分钟,那么其他接口将不进行处理。

如果接口加了加密注解EncryptionAnnotation,并且返回统一的json数据Result类,则自动对数据进行加密。如果是继承了统一父类RequestBase的数据,自动注入时间戳,确保数据的时效性。

如果接口加了解密注解DecryptionAnnotation,并且参数使用RequestBody注解标注,传入json使用统一格式RequestData类,并且内容是继承了包含时间长的父类RequestBase,则自动解密,并且转为对应的数据类型。

功能提供Springboot的starter,实现开箱即用。

代码实现

项目结构

在这里插入图片描述

crypto-common

在这里插入图片描述

crypto-spring-boot-starter 代码结构

在这里插入图片描述

核心代码

crypto.properties AES需要的参数配置

# \u6A21\u5F0F cn.hutool.crypto.Mode
crypto.mode=CTS
# \u8865\u7801\u65B9\u5F0F cn.hutool.crypto.Mode
crypto.padding=PKCS5Padding
# \u79D8\u94A5
crypto.key=tesTKEy123456789
# \u76D0
crypto.iv=testiv1234567890

spring.factories 自动配置文件

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.mry.crypto.config.AppConfig

CryptConfig AES需要的配置参数

package com.mry.crypto.config;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.io.Serializable;

@Configuration
@ConfigurationProperties(prefix = "crypto")
@PropertySource("classpath:crypto.properties")
@Data
@EqualsAndHashCode
@Getter
public class CryptConfig implements Serializable {
    private Mode mode;
    private Padding padding;
    private String key;
    private String iv;
}

AppConfig 自动配置类

package com.mry.crypto.config;
import cn.hutool.crypto.symmetric.AES;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import java.NIO.charset.StandardCharsets;

@Configuration
public class AppConfig {
    @Resource
    private CryptConfig cryptConfig;
    @Bean
    public AES aes() {
        return new AES(cryptConfig.getMode(), cryptConfig.getPadding(), cryptConfig.getKey().getBytes(StandardCharsets.UTF_8), cryptConfig.getIv().getBytes(StandardCharsets.UTF_8));
    }
}
package com.mry.crypto.config;
import cn.hutool.crypto.symmetric.AES;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Configuration
public class AppConfig {
    @Resource
    private CryptConfig cryptConfig;
    @Bean
    public AES aes() {
        return new AES(cryptConfig.getMode(), cryptConfig.getPadding(), cryptConfig.getKey().getBytes(StandardCharsets.UTF_8), cryptConfig.getIv().getBytes(StandardCharsets.UTF_8));
    }
}

DecryptRequestBodyAdvice 请求自动解密

package com.mry.crypto.advice;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mry.crypto.annotation.DecryptionAnnotation;
import com.mry.crypto.common.exception.ParamException;
import com.mry.crypto.constant.CryptoConstant;
import com.mry.crypto.entity.RequestBase;
import com.mry.crypto.entity.RequestData;
import com.mry.crypto.util.AESUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.WEB.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Type;

@ControllerAdvice
public class DecryptRequestBodyAdvice implements RequestBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;
    
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.hasMethodAnnotation(DecryptionAnnotation.class);
    }
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return inputMessage;
    }
    
    @SneakyThrows
    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 获取request
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        if (servletRequestAttributes == null) {
            throw new ParamException("request错误");
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        // 获取数据
        ServletInputStream inputStream = request.getInputStream();
        RequestData requestData = objectMapper.readValue(inputStream, RequestData.class);
        if (requestData == null || StringUtils.isBlank(requestData.getText())) {
            throw new ParamException("参数错误");
        }
        // 获取加密的数据
        String text = requestData.getText();
        // 放入解密之前的数据
        request.setAttribute(CryptoConstant.INPUT_ORIGINAL_DATA, text);
        // 解密
        String decryptText = null;
        try {
            decryptText = AESUtil.decrypt(text);
        } catch (Exception e) {
            throw new ParamException("解密失败");
        }
        if (StringUtils.isBlank(decryptText)) {
            throw new ParamException("解密失败");
        }
        // 放入解密之后的数据
        request.setAttribute(CryptoConstant.INPUT_DECRYPT_DATA, decryptText);
        // 获取结果
        Object result = objectMapper.readValue(decryptText, body.getClass());
        // 强制所有实体类必须继承RequestBase类,设置时间戳
        if (result instanceof RequestBase) {
            // 获取时间戳
            Long currentTimeMillis = ((RequestBase) result).getCurrentTimeMillis();
            // 有效期 60秒
            long effective = 60*1000;
            // 时间差
            long expire = System.currentTimeMillis() - currentTimeMillis;
            // 是否在有效期内
            if (Math.abs(expire) > effective) {
                throw new ParamException("时间戳不合法");
            }
            // 返回解密之后的数据
            return result;
        } else {
            throw new ParamException(String.format("请求参数类型:%s 未继承:%s", result.getClass().getName(), RequestBase.class.getName()));
        }
    }
    
    @SneakyThrows
    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        String typeName = targetType.getTypeName();
        Class<?> bodyClass = Class.forName(typeName);
        return bodyClass.newInstance();
    }
}

EncryptResponseBodyAdvice 相应自动加密

package com.mry.crypto.advice;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mry.crypto.annotation.DecryptionAnnotation;
import com.mry.crypto.common.exception.ParamException;
import com.mry.crypto.constant.CryptoConstant;
import com.mry.crypto.entity.RequestBase;
import com.mry.crypto.entity.RequestData;
import com.mry.crypto.util.AESUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Type;

@ControllerAdvice
public class DecryptRequestBodyAdvice implements RequestBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;
    
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.hasMethodAnnotation(DecryptionAnnotation.class);
    }
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return inputMessage;
    }
    
    @SneakyThrows
    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 获取request
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        if (servletRequestAttributes == null) {
            throw new ParamException("request错误");
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        // 获取数据
        ServletInputStream inputStream = request.getInputStream();
        RequestData requestData = objectMapper.readValue(inputStream, RequestData.class);
        if (requestData == null || StringUtils.isBlank(requestData.getText())) {
            throw new ParamException("参数错误");
        }
        // 获取加密的数据
        String text = requestData.getText();
        // 放入解密之前的数据
        request.setAttribute(CryptoConstant.INPUT_ORIGINAL_DATA, text);
        // 解密
        String decryptText = null;
        try {
            decryptText = AESUtil.decrypt(text);
        } catch (Exception e) {
            throw new ParamException("解密失败");
        }
        if (StringUtils.isBlank(decryptText)) {
            throw new ParamException("解密失败");
        }
        // 放入解密之后的数据
        request.setAttribute(CryptoConstant.INPUT_DECRYPT_DATA, decryptText);
        // 获取结果
        Object result = objectMapper.readValue(decryptText, body.getClass());
        // 强制所有实体类必须继承RequestBase类,设置时间戳
        if (result instanceof RequestBase) {
            // 获取时间戳
            Long currentTimeMillis = ((RequestBase) result).getCurrentTimeMillis();
            // 有效期 60秒
            long effective = 60*1000;
            // 时间差
            long expire = System.currentTimeMillis() - currentTimeMillis;
            // 是否在有效期内
            if (Math.abs(expire) > effective) {
                throw new ParamException("时间戳不合法");
            }
            // 返回解密之后的数据
            return result;
        } else {
            throw new ParamException(String.format("请求参数类型:%s 未继承:%s", result.getClass().getName(), RequestBase.class.getName()));
        }
    }
    
    @SneakyThrows
    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        String typeName = targetType.getTypeName();
        Class<?> bodyClass = Class.forName(typeName);
        return bodyClass.newInstance();
    }
}

crypto-test 代码结构

在这里插入图片描述

核心代码

application.yml 配置文件

spring:
  mvc:
    format:
      date-time: yyyy-MM-dd HH:mm:ss
      date: yyyy-MM-dd
  # 日期格式化
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
server:
  port: 9999

Teacher 实体类

package com.mry.crypto.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Teacher extends RequestBase implements Serializable {
    @NotBlank(message = "姓名不能为空")
    private String name;
    @NotNull(message = "年龄不能为空")
    @Range(min = 0, max = 150, message = "年龄不合法")
    private Integer age;
    @NotNull(message = "生日不能为空")
    private Date birthday;
}

TestController 测试Controller

package com.mry.crypto.controller;
import com.mry.crypto.annotation.DecryptionAnnotation;
import com.mry.crypto.annotation.EncryptionAnnotation;
import com.mry.crypto.common.entity.Result;
import com.mry.crypto.common.entity.ResultBuilder;
import com.mry.crypto.entity.Teacher;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController implements ResultBuilder {
    
    @PostMapping("/get")
    public ResponseEntity<Result<?>> get(@Validated @RequestBody Teacher teacher) {
        return success(teacher);
    }
    
    @PostMapping("/encrypt")
    @EncryptionAnnotation
    public ResponseEntity<Result<?>> encrypt(@Validated @RequestBody Teacher teacher) {
        return success(teacher);
    }
    
    @PostMapping("/encrypt1")
    @EncryptionAnnotation
    public Result<?> encrypt1(@Validated @RequestBody Teacher teacher) {
        return success(teacher).getBody();
    }
    
    @PostMapping("/decrypt")
    @DecryptionAnnotation
    public ResponseEntity<Result<?>> decrypt(@Validated @RequestBody Teacher teacher) {
        return success(teacher);
    }
}

验证

加密:

在这里插入图片描述

解密:

在这里插入图片描述

到此这篇关于Spring Boot 接口加解密的文章就介绍到这了,更多相关Spring Boot 接口加解密内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章