From 9f8e2ca57ba644573a0165085de34e449fce91de Mon Sep 17 00:00:00 2001 From: zy <276996223@qq.com> Date: Tue, 11 Feb 2025 13:58:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=8F=E7=A8=8B=E5=BA=8F=E6=B6=88=E6=81=AF?= =?UTF-8?q?=E6=8E=A8=E9=80=81token?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/weixin/TokenValidatorService.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/weixin/TokenValidatorService.java diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/weixin/TokenValidatorService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/weixin/TokenValidatorService.java new file mode 100644 index 0000000..1477435 --- /dev/null +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/weixin/TokenValidatorService.java @@ -0,0 +1,38 @@ +package cn.iocoder.yudao.module.system.service.weixin; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +public class TokenValidatorService { + public static boolean validateToken(String token, String signature, String timestamp, String nonce) { + String[] arr = new String[]{token, timestamp, nonce}; + // 对 token、timestamp 和 nonce 按字典序排序 + Arrays.sort(arr); + StringBuilder content = new StringBuilder(); + for (String s : arr) { + content.append(s); + } + String tempStr = sha1Encode(content.toString()); + // 将加密后的字符串与 signature 进行对比 + return tempStr!= null && tempStr.equals(signature); + } + private static String sha1Encode(String str) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-1"); + digest.update(str.getBytes()); + byte[] bytes = digest.digest(); + StringBuilder hexStr = new StringBuilder(); + for (byte b : bytes) { + String hex = Integer.toHexString(0xFF & b); + if (hex.length() == 1) { + hexStr.append('0'); + } + hexStr.append(hex); + } + return hexStr.toString(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return null; + } +} \ No newline at end of file