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; } }