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){
|
SymmetricCrypto sm4 = SmUtil.sm4(KEY.getBytes());
|
return sm4.decryptStr(encryptContext, CharsetUtil.CHARSET_UTF_8);
|
}
|
|
/**
|
* 测试方法,测试完要记得删除掉
|
*/
|
public static void main(String[] args) {
|
// 自定义秘钥
|
String secretKey = "csdn1024CSDN1024";
|
|
JSONObject jsonObject = new JSONObject();
|
jsonObject.put("name", "csdn");
|
jsonObject.put("desc","1024程序员节");
|
|
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("d2f1da26d73f31d8f66ea64b23beebe014345f504ca516579dce993e4a527b48bc242f17941c7cb6d3eeb60bfe6175a51dafb387fa67a655fb18084acf6f68d149b14b6b9bb0063a7714ae24df78e064250b7bcd7847a719a69328ffaaa2d3add6d002b44fcc4610f3661f7611031cd410325c8391a7227ded9f6c4ec8d8a9908ae19c93c4fb2a16501738055acbea0925500bf691703c2ad4e1b172679d38da");
|
System.out.println(String.format("解密后的信息: %s", decryptInfo));
|
}
|
|
}
|