Browse Source

小程序消息推送token

master
zy 2 months ago
parent
commit
9f8e2ca57b
  1. 38
      yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/weixin/TokenValidatorService.java

38
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;
}
}
Loading…
Cancel
Save