无关风月
2 天以前 ce0651907f18a57dae80065e01589e975530f53e
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
package com.ruoyi.common.utils;
 
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
 
/**
 * @Author 国密4工具类
 * @Description 数据加密解密
 **/
public class Sm4Utils {
 
 
    // 示例密钥,实际应用中应使用安全的方式生成和存储密钥
    private static final String KEY = "2022lab02ora12to";
    /**
     * sm4数据加密
     * @param params 参数信息
     * @return 加密后的值
     */
    public static String sm4EncryptUtil(String params){
        SymmetricCrypto sm4 = SmUtil.sm4(KEY.getBytes());
        return sm4.encryptHex(params);
    }
 
    /**
     * sm4数据解密
     * @param encryptContext 加密的内容
     * @return 解密后的值
     */
    public static String sm4DecryptUtil(String encryptContext){
        JSONObject jsonObject = JSONObject.parseObject(encryptContext);
        String param = jsonObject.getString("param");
        SymmetricCrypto sm4 = SmUtil.sm4(KEY.getBytes());
        return sm4.decryptStr(param, CharsetUtil.CHARSET_UTF_8);
    }
 
    /**
     * 测试方法,测试完要记得删除掉
     */
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageNum", 1);
        jsonObject.put("pageSize",10);
        String strParams = JSON.toJSONString(jsonObject);
        System.out.println(String.format("明文参数: %s", strParams));
 
        String encryptContext = sm4EncryptUtil(strParams);
        System.out.println(String.format("加密后的值: %s", encryptContext));
        String decryptInfo = sm4DecryptUtil(encryptContext);
        System.out.println(String.format("解密后的信息: %s", decryptInfo));
    }
 
}