【加解密】前后端接口交互使用AES加解密

时间:2025-02-07 14:30:26

【开发背景】

接口数据加解密是前后端分离开发非常常见的应用场景。

前端:vue3+typescript+vite

后端:SpringBoot

【前端代码】

1. 安装crypto-js

npm install crypto-js

2. src/utils下新建

import CryptoJS from 'crypto-js'

export interface CrypotoType {
  encrypt: any
  decrypt: any
}

// 默认的 KEY 与 iv 如果没有给
const KEY = .('yourkeycodexxxx')
const IV = .('yourivcodexxxx')

/**
 * AES加密 :字符串 key iv  返回base64
 */
export function Encrypt(word: any, keyStr?: any, ivStr?: any) {
  let key = KEY
  let iv = IV
  if (keyStr) {
    key = .(keyStr)
    iv = .(ivStr)
  }
  const srcs = .(word)
  const encrypted = (srcs, key, {
    iv: iv,
    mode: ,
    padding: 
  })
  return .()
}

/**
 * AES 解密 :字符串 key iv  返回base64
 *
 * @return {string}
 */
export function Decrypt(word: any, keyStr?: any, ivStr?: any) {
  let key = KEY
  let iv = IV

  if (keyStr) {
    key = .(keyStr)
    iv = .(ivStr)
  }

  const base64 = .(word)
  const src = .(base64)

  const decrypt = (src, key, {
    iv: iv,
    mode: ,
    padding: 
  })

  return .(decrypt)
}

需要注意的是,在转化成字符串的过程中一定要指定编码格式为UTF-8。

3. 在request/response拦截器里进行加密解密

/src/http/

// 引入AES加解密
import { Encrypt, Decrypt } from '@/utils/'

(1)请求发送之前,对请求数据进行加密处理

 = Encrypt(())
!['Content-Type'] = 'application/json' // 指定传送数据格式为JSON

(2)接收数据之前,对接收数据进行解密处理

 = (Decrypt())

完整代码

/** 封装axios **/
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { Toast } from 'vant'
// 引入AES加解密
import { Encrypt, Decrypt } from '@/utils/'

// axios配置
const config = {
  // baseURL: '/server-address/', // 发布地址
  baseURL: 'http://localhost:8080/', // 本地测试地址
  timeout: 5000 // request timeout
}

// 定义返回值类型
export interface Result<T = any> {
  code: number,
  msg: string,
  data: T
}

// axios封装
class Http {
  // 定义一个axios的实例
  private instance: AxiosInstance

  // 构造函数:初始化
  constructor(config: AxiosRequestConfig) {
    // 创建axios实例
     = (config)
    // 配置拦截器
    ()
  }

  // 拦截器:处理请求发送和请求返回的数据
  private interceptors() {

    // 请求发送之前的处理
    ((config: AxiosRequestConfig) => {
      ()
      /** 数据加密 json -> string -> encrypt **/
       = Encrypt(())
      // 修改headers的Content-Type
      !['Content-Type'] = 'application/json'
      /** 在请求头部添加token **/
      // let token = ''; // 从cookies/sessionStorage里获取
      // if(token){
      //   // 添加token到头部
      //   !['token'] = token
      // }
      return config
    }, error => {
       = {}
       = '服务器异常,请联系管理员!'
      return error
    })

    // 请求返回数据的处理
    ((response: AxiosResponse) => {
      const { data } = response
      // 数据不解密
      const res = data
      // 数据整体解密 decrypt -> string -> JSON
      // const res = (Decrypt(data))
      // 数据部分解密
      if(!==null){
         = (Decrypt())
      }
      (res) // res: { code: 200, data: null, msg: '请求成功' }

      if ( !== 200) {
        Toast({
          message:  || '服务器出错!',
          type: 'fail',
          duration: 5 * 1000
        })
        return (new Error( || '服务器出错!'))
      } else {
        return res
      }
    }, error => {
      ('进入错误')
       = {}
      if (error && ) {
        switch () {
          case 400:
             = '错误请求'
            break
          case 500:
             = '服务器内部错误'
            break
          case 404:
             = '请求未找到'
            break
          default:
             = `连接错误${}`
            break
        }
        Toast({
          message:  || '服务器连接出错!',
          type: 'fail',
          duration: 5 * 1000
        })
      } else {
         = '连接到服务器失败!'
        Toast({
          message: ,
          type: 'fail',
          duration: 5 * 1000
        })
      }
      return (error)
    })
  }

  /** RestFul api封装 **/
  // Get请求:注意这里params被解构了,后端获取参数的时候直接取字段名
  get<T = Result>(url: string, params?: object): Promise<T> {
    return (url, { params })
  }

  // Post请求
  post<T = Result>(url: string, data?: object): Promise<T> {
    return (url, data)
  }

  // Put请求
  put<T = Result>(url: string, data?: object): Promise<T> {
    return (url, data)
  }

  // DELETE请求
  delete<T = Result>(url: string): Promise<T> {
    return (url)
  }
}
export default new Http(config)

【后端代码】

后端采用自定义注解的方式进行加解密。

1. 引入相关jar包

<!-- AES 密码解密 -->
<dependency>
    <groupId></groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.60</version>
</dependency>
<!-- Base64依赖 -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>

2. package.annotation新建2个注解EncryptDecrypt

package ;

import ;
import ;
import ;
import ;

/** 自定义解密方法:可以放在方法上,也可以放在参数上单独解密 **/
@Retention()
@Target({, })
public @interface Decrypt {
}
package ;

import ;
import ;
import ;
import ;

/** 自定义加密方法,仅能放在方法上 **/
@Retention()
@Target()
public @interface Encrypt {
}

3. 下新建工具类

package ;

import .Base64;

import ;
import ;
import ;
import ;
import ;

/**
 * @author YSK
 * @date 2020/8/24 13:13
 */
public  class SecretUtils {
    /***
     * key和iv值可以随机生成
     */
    private static String KEY = "yourkeycodexxxx";

    private static String IV = "yourivcodexxxx";

    /***
     * 加密
     * @param  data 要加密的数据
     * @return encrypt
     */
    public static String encrypt(String data){
        return encrypt(data, KEY, IV);
    }

    /***
     * param data 需要解密的数据
     * 调用desEncrypt()方法
     */
    public static String desEncrypt(String data){
        return desEncrypt(data, KEY, IV);
    }

    /**
     * 加密方法
     * @param data  要加密的数据
     * @param key 加密key
     * @param iv 加密iv
     * @return 加密的结果

     */
    private static String encrypt(String data, String key, String iv){
        try {
            //"算法/模式/补码方式"NoPadding PkcsPadding
            Cipher cipher = ("AES/CBC/NoPadding");
            int blockSize = ();

            byte[] dataBytes = (StandardCharsets.UTF_8);
            int plaintextLength = ;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            (dataBytes, 0, plaintext, 0, );

            SecretKeySpec keyspec = new SecretKeySpec((StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivspec = new IvParameterSpec((StandardCharsets.UTF_8));

            (Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = (plaintext);

            return new Base64().encodeToString(encrypted);

        } catch (Exception e) {
            ();
            return null;
        }
    }

    /**
     * 解密方法
     * @param data 要解密的数据
     * @param key  解密key
     * @param iv 解密iv
     * @return 解密的结果
     */
    private static String desEncrypt(String data, String key, String iv){
        try {
            byte[] encrypted1 = new Base64().decode(data);

            Cipher cipher = ("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec((StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec((StandardCharsets.UTF_8));
            (Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] original = (encrypted1);
            return new String(original, StandardCharsets.UTF_8).trim();
        } catch (Exception e) {
            ();
            return null;
        }
    }
}

4. 下新建

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;

/** 解密请求数据 **/
@ControllerAdvice
public class DecryptRequest extends RequestBodyAdviceAdapter {

    /**
     * 该方法用于判断当前请求,是否要执行beforeBodyRead方法
     *
     * @param methodParameter handler方法的参数对象
     * @param targetType      handler方法的参数类型
     * @param converterType   将会使用到的Http消息转换器类类型
     * @return 返回true则会执行beforeBodyRead
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return () || ();
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        byte[] body = new byte[().available()];
        ().read(body);
        try {
            String str = new String(body);
            String newStr = (str); // 解密加密串
            // str->inputstream
            /** 注意编码格式一定要指定UTF-8 不然会出现前后端解密错误 **/
            InputStream newInputStream = new ByteArrayInputStream((StandardCharsets.UTF_8));
            return new HttpInputMessage() {
                @Override
                public InputStream getBody() throws IOException {
                    return newInputStream; // 返回解密串
                }

                @Override
                public HttpHeaders getHeaders() {
                    return ();
                }
            };
        }catch (Exception e){
            ();
        }
        return (inputMessage, parameter, targetType, converterType);
    }
}

5. 下新建

package ;

import .;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

/** 加密返回数据 **/
@ControllerAdvice
public class EncryptResponse implements ResponseBodyAdvice<ResultVO> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return ();
    }

    @Override
    public ResultVO beforeBodyWrite(ResultVO body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        try{
//            if(()!=null){
//                ((()));
//            }
            if(()!=null){ // 加密传输数据,注意先转JSON再转String格式
                (((())));
            }
        }catch (Exception e){
            ();
        }
        return body;
    }
}

6.在controller里对需要使用的方法或者参数加上@Encrypt或者@Decrypt注解即可

// 查询
@GetMapping("/list")
@Encrypt
public ResultVO projectList(@RequestHeader(name = "user") String userId, String queryType) {
    try {
            List<Project> list = (userId, queryType);
            return ("查询projectList列表成功!", list);
        } catch (Exception e) {
            return (());
        }
}
// 更新项目状态
@PutMapping("/updatestatus")
@Decrypt
public ResultVO updateStatus(@RequestBody JSONObject data) {
    if ((("id"), ("type")) == 1) {
        return ("项目状态修改成功!", null);
      }
        return ("项目状态修改失败");
 }

【小结】

请注意前后端加解密一定要统一指定对应的编码格式,这里全部指定成了UTF-8

初版本没有指定编码格式,本地测试没有任何问题,发布到服务器后出现了很多bug,排查原因都是由于编码格式不一致导致的。

只要涉及到字符串转换的、字节流的全部要指定编码格式,请务必注意这一点。

遇到的bug

前端报错=> Error: Malformed UTF-8 data

后端报错=> JSON parse error: Invalid UTF-8 middle 0xc2

参考资料:SpringBoot接口加密与解密_魅Lemon的博客-****博客_springboot 接口加密