引入jar:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
验签代码块
package com.example.demo.util;
import org.apache.commons.codec.digest.DigestUtils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Locale;
import java.util.UUID;
/**
* @description: 验签
* @create: 2020/05/14 21:34
**/
public class SignUtil {
/**
* 验签
* @param token
* @param timestamp 时间戳
* @param nonce 随机数
* @param signature 签名
* @return
*/
public static boolean checkSignature(String token, String timestamp, String nonce, String signature){
//1. 加签
String newSignature = getSignature(token, timestamp, nonce);
//2. 将sha1加密后的字符串和signature对比,判断该请求来源是否合法
return newSignature != null ? newSignature.equals(signature.toUpperCase(Locale.ENGLISH)) : false;
}
/**
* 生成签名
* @param token
* @param timestamp
* @param nonce
* @return
*/
public static String getSignature(String token, String timestamp, String nonce){
//1. 将token、timestamp、nonce三个参数进行字典排序
String[] arr = new String[]{token, timestamp, nonce};
Arrays.sort(arr);
//2. 把排序后的三个参数token、timestamp、nonce进行拼接
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]);
}
//3. sha1加密
String newSignature = sha1Method1(sb.toString());
System.out.println(newSignature);
String newSignature2 = sha1Method2(sb.toString());
System.out.println(newSignature2);
return newSignature;
}
/**
* 加密算法 -- 方法一【推荐】
* @param decript
* @return
*/
public static String sha1Method1(String decript){
return DigestUtils.sha1Hex(decript);
}
/**
* 加密算法 -- 方法二
* @param decript
* @return
*/
public static String sha1Method2(String decript) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
// 字节数组转换为 十六进制 数
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) {
String timestamp = Long.toString(System.currentTimeMillis() / 1000);
String nonce = UUID.randomUUID().toString();
String token = "token";
System.out.println("token = " + token + ",timestamp = " + timestamp + ",nonce = " + nonce);
getSignature(token, timestamp, nonce);
}
}
运行结果:
token = token,timestamp = 1589468072,nonce = 52be99ff-15f8-4109-81e3-2399a07b7cc9
38f0da3222a9151edae3126e7a3292cc85acd53d
38f0da3222a9151edae3126e7a3292cc85acd53d
本文介绍了一种基于SHA-1算法的签名验证方法,使用了commons-codec库进行加密处理,详细展示了如何生成和验证签名,适用于微信公众号等场景的安全通信。
2205

被折叠的 条评论
为什么被折叠?



