From 2efbef8e3973f534c50cb4cec50de91dda1b17a9 Mon Sep 17 00:00:00 2001 From: cwchen <1048842385@qq.com> Date: Tue, 16 Sep 2025 17:17:10 +0800 Subject: [PATCH] =?UTF-8?q?SM3=E5=8A=A0=E5=AF=86=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/utils/encryption/Sm3Util.java | 39 ++++++++++++++++--- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/bonus-common/src/main/java/com/bonus/common/utils/encryption/Sm3Util.java b/bonus-common/src/main/java/com/bonus/common/utils/encryption/Sm3Util.java index a481b21..176b6d3 100644 --- a/bonus-common/src/main/java/com/bonus/common/utils/encryption/Sm3Util.java +++ b/bonus-common/src/main/java/com/bonus/common/utils/encryption/Sm3Util.java @@ -1,5 +1,7 @@ package com.bonus.common.utils.encryption; +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.io.IoUtil; import cn.hutool.crypto.SmUtil; import cn.hutool.crypto.digest.SM3; @@ -14,18 +16,45 @@ import java.nio.charset.StandardCharsets; */ public class Sm3Util { - static SM3 sm3 = SmUtil.sm3WithSalt("2cc0c5f9f1749f1632efa9f63e902323".getBytes(StandardCharsets.UTF_8)); - + private static final String SALT = "2cc0c5f9f1749f1632efa9f63e902323"; public static String encrypt(String data) { - return Sm3Util.sm3.digestHex(data); + try { + // 与前端的处理方式完全一致:字符串拼接 + SM3哈希 + String dataWithSalt = SALT + data; + SM3 sm3 = SmUtil.sm3(); + return sm3.digestHex(dataWithSalt); + } catch (Exception e) { + throw new RuntimeException("SM3 encryption failed", e); + } } + // 其他方法也需要相应修改 public static String encrypt(InputStream data) { - return Sm3Util.sm3.digestHex(data); + // 对于流数据,需要先读取内容再拼接 + try { + String content = IoUtil.readUtf8(data); + String dataWithSalt = SALT + content; + SM3 sm3 = SmUtil.sm3(); + return sm3.digestHex(dataWithSalt); + } catch (Exception e) { + throw new RuntimeException("SM3 encryption failed", e); + } } public static String encrypt(File dataFile) { - return Sm3Util.sm3.digestHex(dataFile); + try { + String content = FileUtil.readUtf8String(dataFile); + String dataWithSalt = SALT + content; + SM3 sm3 = SmUtil.sm3(); + return sm3.digestHex(dataWithSalt); + } catch (Exception e) { + throw new RuntimeException("SM3 encryption failed", e); + } } + + public static void main(String[] args) { + System.out.println(Sm3Util.encrypt("pageNum=1&pageSize=10")); + } + } \ No newline at end of file