guyue
4 天以前 8f5cb469b825cce61734c84fd633f0dfc3000ee6
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
package com.linghu.utils;
 
 
import cn.afocus.crypt.sign.UserSign;
 
import cn.afocus.crypt.sign.UserSign;
import com.alibaba.fastjson.JSON;
import com.linghu.model.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import javax.annotation.PostConstruct;
 
@Component
public class OpenCryptUtil {
 
    // 加密密钥(从配置文件读取,避免硬编码)
    @Value("${app.crypt.secret-key}") // 长度需符合算法要求(如AES-256需32位)
    private String secret;
 
    // 初始化向量(CBC模式需要,可选)
//    @Value("${app.crypt.iv:1234567890abcdef}") // 16位(AES-128/256通用)
//    private String iv;
 
    // 初始化加密配置(若需要)
    @PostConstruct
    public void init() {
        // 若 open-crypt 需要初始化,可在此处处理
        // 例如:CryptoUtils.init(secretKey, iv);
    }
 
    /**
     * AES加密(假设 open-crypt 默认使用AES-CBC模式)
     */
    public String encrypt(User user) {
        try {
            // 调用 open-crypt 的加密方法(根据实际API调整)
            //user转为 json
            String json = JSON.toJSONString(user);
            return UserSign.gen(json, "fY9tX7vX7qH5bN2cD8eM4xD2fH7uL4xM".getBytes());
        } catch (Exception e) {
            throw new RuntimeException("加密失败:" + e.getMessage(), e);
        }
    }
 
    /**
     * AES解密
     */
    public String decrypt(String token) {
        try {
            // 调用 open-crypt 的解密方法
            return UserSign.decrypt(token, "fY9tX7vX7qH5bN2cD8eM4xD2fH7uL4xM".getBytes());
        } catch (Exception e) {
            throw new RuntimeException("解密失败:" + e.getMessage(), e);
        }
    }
}