liujie
2026-03-19 ce4c8b355b209826aa06f60b532988107349df41
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.xiaopeng.account.util;
 
import com.alibaba.fastjson2.JSONObject;
import com.xiaopeng.common.core.utils.AESUtil;
import com.xiaopeng.common.core.utils.RSAUtil;
import com.xiaopeng.common.redis.service.RedisService;
import org.springframework.stereotype.Component;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
 
/**
 * 参数加解密工具类
 */
@Component
public class EncryptionDecryptionUtil {
 
    @Resource
    private RedisService redisService;
 
 
    /**
     * 解密
     * @param content
     * @return
     */
    public String decrypt(String content, HttpServletRequest request) {
        //根据用户sessionId获取用户私钥
        String sessionId = request.getSession().getId();
        Object cacheObject = redisService.getCacheObject("session:id:" + sessionId);
        if (null != cacheObject) {
            return content;
        }
        JSONObject jsonObject = JSONObject.parseObject(cacheObject.toString());
        String privateKey = jsonObject.getString("privateKey");
        String xps = request.getHeader("xps");
        //使用用户私钥解密xps获取AES密钥
        String aes_key = RSAUtil.decryptByPrivateKey(xps, privateKey);
        //使用AES密钥解密content
        String decrypt = AESUtil.decryptByCBC(content, aes_key, AESUtil.generateIV());
        //删除用户密钥对,保证秘钥不泄露
        redisService.deleteObject("session:id:" + sessionId);
        return decrypt;
    }
 
 
    /**
     * 加密
     * @param content      待加密内容
     * @param privateKey   ARS私钥
     * @return
     */
    public static JSONObject encrypt(String content, String privateKey) {
        //生成 AES 密钥和 IV
        String iv = AESUtil.generateIV();
        //使用用户私钥加密AES密钥
        String aes_key = AESUtil.generateKey(AESUtil.KEY_LENGTH_256);
        //使用AES密钥加密content
        String encrypt = AESUtil.encryptByCBC(content, aes_key, iv);
        //使用用户私钥加密AES密钥
        String encryptAESKey = RSAUtil.encryptByPrivateKey(aes_key, privateKey);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("iv", iv);
        jsonObject.put("aes_key", encryptAESKey);
        jsonObject.put("content", encrypt);
        return jsonObject;
    }
}