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