前后端分离数据传输加解密方案(建议方案二)

方案一  请求响应参数全部加密

1.优缺点

      a.优点:实现简单,比明文传输安全

      b.缺点:1)由于加密所有参数,效率低下 2)信息全加密,不利于前后端联调  3)密钥传输不安全,容易被拦截

       优化点:前端生成AES对称加密密钥,用rsa私钥非对称加密将AES密钥加密,传给到后端,后端用rsa公钥解密后获取到AES密钥,这样前后端就有了公共的AES密钥了

2.开发步骤(AES对称加密)    

  加密流程:

      a.前端调用接口/web/security/v1/getAesKey 并将其保存在sesssionStrage中

      b.后端在前端调用/web/security/v1/getAesKey时,生成AES密钥并保存在session中,并返回给前端

      c.前端访问其他接口传入的参数都用此AES密钥加密,接收到的响应数据都用此AES密钥解密,可以拦截器,对所有请求和响应加解密

      d.后端和前端一样用此AES密钥进行加解密

 前端加解密

<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.min.js"></script>

/**
* 加密
**/
function encrypt(value,key) {
    var tempValue = JSON.stringify(value);
 var tempKey = CryptoJS.enc.Utf8.parse(key);
 var srcs = CryptoJS.enc.Utf8.parse(tempValue); 
 var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, 
  padding:CryptoJS.pad.Pkcs7 });
  var encryptedValue = encrypted.toString();
   return encryptedValue;
}


/**
*解密
**/
 function decrypt(value,key) {
	var keyStr = CryptoJS.enc.Utf8.parse(key)
    var decrypt = CryptoJS.AES.decrypt(value, keyStr, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
    return CryptoJS.enc.Utf8.stringify(decrypt).toString()
 }
 

b.后端加解密

  public class AesEncrypt {

 /**
     * 加密
     *
     * @param value数据
     * @param key  密钥
     * @return 加密后内容
     */
    public static byte[] encrypt(byte[] value, String key) throw Exception{
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("UTF-8"), "AES"));
            return cipher.doFinal(value);
       
    }

 /**
     * 解密
     *
     * @param value数据
     * @param key  密钥
     * @return 解密后内容
     */
    public static  byte[] decrypt(byte[] value, String key) throw Exception {
  
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            //使用密钥初始化,设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            //执行操作
            return cipher.doFinal(value);

        
    }
}

c.后端拦截代码实现

/**
* 请求过滤器,记得注册
**/
public EncryptFilter implements Filter {


 @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        LOGGER.debug("进入加解密过滤器,URI:{}", uri);
        HttpServletResponse response = (HttpServletResponse) servletResponse;
       AesHttpServletRequestWrapper aesHttpServletRequestWrapper = new AesHttpServletRequestWrapper(request);
        filterChain.doFilter(aesHttpServletRequestWrapper, response);
       
    }


}
/**
* (1)请求拦截,解密
**/
public class AesHttpServletRequestWrapper extends HttpServletRequestWrapper {

     private String bodyContent;
     private Parameters parameters = new Parameters();
     private HttpServletRequest request;

     public AesHttpServletRequestWrapper (HttpServletRequest request) {
    request = request;
    initWrapper();
  }

private void initWrapper() {
      this.parameters.setCharset(charset);
      readBodyBytes();
      this.parseParameterMap();
  }  

 private void readBodyBytes() {
    if (this.bodyContent == null) {
      try {
        byte[] bodyBytes = readInputBody(request.getInputStream());
        this.bodyContent = new String(AesEncrypt.decrypt(bodyBytes), charset);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }  

 private byte[] readInputBody(InputStream 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();
    return byteArrayOutputStream.toByteArray();
  }  
  
  @Override
  public String getQueryString() {
    return queryString;
  }

  @Override
  public String getParameter(String name) {
    String[] values = getParameterValues(name);
    return values == null || values.length == 0 ? null : values[0];
  }
  @Override
  public int getContentLength() {
    return bodyContent.getBytes(charset).length;
  }

  @Override
  public long getContentLengthLong() {
    return bodyContent.getBytes(charset).length;
  }

     @Override
  public Map<String, String[]> getParameterMap() {
    if (paramsMap == null) {
      paramsMap = new HashMap<>();
      Enumeration<String> nameEnum = this.parameters.getParameterNames();
      while (nameEnum.hasMoreElements()) {
        String name = nameEnum.nextElement();
        paramsMap.put(name, getParameterValues(name));
      }
    }
    return paramsMap;
  }

  @Override
  public Enumeration<String> getParameterNames() {
    return this.parameters.getParameterNames();
  }

  @Override
  public String[] getParameterValues(String name) {
    return parameters.getParameterValues(name);
  }
}
/**
* (2) 响应拦截 加密
**/

@ControllerAdvice
public class AesResponseAdvice implements ResponseBodyAdvice<Object> {
        
    private static final String AES_KEY= "AES_KEY";
  


      @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> converterClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        ServletServerHttpRequest request = (ServletServerHttpRequest) serverHttpRequest;
        if (body != null) {
            ServletServerHttpResponse response = (ServletServerHttpResponse) serverHttpResponse;
            try {
                byte[] contentBytes = null;
                    contentBytes = String.valueOf(body).getBytes(Charset.forName("UTF-8"));
                 Object aesKey = request.getServletRequest().getSession().getAttribute(AES_KEY);
               body = AesEncrypt.encrypt(contentBytes,String.value(aesKey));
                
            } catch (IOException e) {
                LOGGER.error("加密数据失败", e);
            }
        }
        return body;
    }

}

方案一  请求响应参数自定义加密字段(比如id)

1.优缺点

     a.优点:效率高,只加密某些重要字段

     b.缺点:实现复杂

2.开发步骤

   a.自定义注解 @Encrypt,放属性上或者参数上

@JacksonAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface Encrypt {
    String value() default "";
    String fieldName() default "";
    String[] ignoreValue() default {};
}

b.springmvc中增加请求参数解析器,响应参数解析器

public class EncryptRequestParamMethodArgumentResolver extends RequestParamMethodArgumentResolver {
    IEncryptionService encryptionService;

    @Override
    @Nullable
    protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
        Object result = super.resolveName(name, parameter, request);
        if (EncryptContext.isEncrypt() && result != null && parameter.hasParameterAnnotation(Encrypt.class)) {
            Encrypt encrypt = parameter.getParameterAnnotation(Encrypt.class);
            if (result instanceof String && !EncryptUtils.ignoreValue(encrypt, (String) result)) {
                if (isArray(parameter)) {
                    result = ((String) result).split(",");
                } else {
                    result = encryptionService.decrypt(((String) result), encrypt.value());
                    return result;
                }
            }
            if (result instanceof String[]) {
                String[] oldResult = (String[]) result;
                String[] newResult = new String[oldResult.length];
                for (int i = 0; i < oldResult.length; i++) {
                    if (EncryptUtils.ignoreValue(encrypt, oldResult[i])) {
                        newResult[i] = oldResult[i];
                    } else {
                        newResult[i] = encryptionService.decrypt(oldResult[i], encrypt.value());
                    }
                }
                return newResult;
            }
        }
        return result;
    }
public class EncryptRequestResponseBodyMethodProcessor extends RequestResponseBodyMethodProcessor {

    @Override
    public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
        if (!EncryptContext.isEncrypt()) {
            return super.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
        }
        Encrypt encrypt = parameter.getParameterAnnotation(Encrypt.class);
        if (encrypt == null) {
            return super.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
        }
        // 如果是集合类,且范型类型是基础类型的包装类型
        if (Collection.class.isAssignableFrom(parameter.getParameterType())) {
            return resolveCollectionArgument(parameter, mavContainer, webRequest, binderFactory, encrypt);
        }
        // 如果是集合类,且范型类型是基础类型的包装类型
        if (parameter.getParameterType().isArray()) {
            return resolveArrayArgument(parameter, mavContainer, webRequest, binderFactory, encrypt);
        }
        // 如果是 Map 类,且泛型类型是基础类型顶的包装类型
        if (Map.class.isAssignableFrom(parameter.getParameterType())) {
            return resolveMapArgument(parameter, mavContainer, webRequest, binderFactory, encrypt);
        }
        return super.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
    }
    
}

c.将请求,响应参数解析器,加入到springmvc解析器列表中HandlerMethodArgumentResolver

public class WebBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {
    @Nullable
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RequestMappingHandlerAdapter) {
            RequestMappingHandlerAdapter adapter = (RequestMappingHandlerAdapter) bean;
            List<HandlerMethodArgumentResolver> currentResolvers = adapter.getArgumentResolvers();
            if (currentResolvers == null) {
                throw new IllegalStateException(
                        String.format("No HandlerMethodArgumentResolvers found in RequestMappingHandlerAdapter %s!", beanName));
            }
            //IEncryptionService encryptionService = new EncryptionService();
            //替换PathVariableMethodArgumentResolver 和 RequestParamMethodArgumentResolver
            PathVariableMethodArgumentResolver pathVariableMethodArgumentResolver = new EncryptPathVariableMethodArgumentResolver(encryptionService);
            RequestParamMethodArgumentResolver requestParamMethodArgumentResolverFalse = new EncryptRequestParamMethodArgumentResolver(encryptionService, beanFactory, false);
            RequestParamMethodArgumentResolver requestParamMethodArgumentResolverTrue = new EncryptRequestParamMethodArgumentResolver(encryptionService, beanFactory, true);
            EncryptRequestResponseBodyMethodProcessor encryptRequestResponseBodyMethodProcessor;
            try {
                encryptRequestResponseBodyMethodProcessor = new EncryptRequestResponseBodyMethodProcessor(adapter.getMessageConverters(),
                        (List<Object>) FieldUtils.readDeclaredField(adapter, "requestResponseBodyAdvice", true));
            } catch (IllegalAccessException e) {
                throw new CommonException(e);
            }
            encryptRequestResponseBodyMethodProcessor.setEncryptionService(encryptionService);
            List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>(adapter.getArgumentResolvers().size());
            //spring 默认注册了2个requestParamMethodArgumentResolver
            boolean isFirst = true;
            for (HandlerMethodArgumentResolver resolver : adapter.getArgumentResolvers()) {
                if (resolver instanceof PathVariableMethodArgumentResolver) {
                    resolvers.add(pathVariableMethodArgumentResolver);
                    continue;
                }
                if (resolver instanceof RequestParamMethodArgumentResolver) {
                    if (isFirst) {
                        resolvers.add(requestParamMethodArgumentResolverFalse);
                        isFirst = false;
                        continue;
                    }
                    resolvers.add(requestParamMethodArgumentResolverTrue);
                    continue;
                }
                if (resolver instanceof RequestResponseBodyMethodProcessor) {
                    resolvers.add(encryptRequestResponseBodyMethodProcessor);
                    continue;
                }
                resolvers.add(resolver);
            }
            adapter.setArgumentResolvers(resolvers);
            
}

3.实现效果