import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.util.Locale; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; /** * 优时开放平台 · 回调验签示例(Java 11+,单文件、无第三方依赖) * *
* 签名串:METHOD + "\n" + path + "\n" + X-Timestamp + "\n" + X-Nonce + "\n" + sha256_hex(body)
* 签名: lower_hex(HMAC-SHA256(sign_key, 签名串)),与请求头 X-Sign 比较(常量时间)
* path 是你的回调地址的路径部分,不含域名和查询参数,例如 /notify
* body 必须使用原始请求体字节(不要先反序列化再序列化)
*
* 处理建议:验签失败返回 401;按 event_id 去重;处理成功后 5 秒内返回 HTTP 200,响应体为 success。
*
* 在 Spring MVC 中使用(示意):
* byte[] body = StreamUtils.copyToByteArray(request.getInputStream());
* boolean ok = WebhookVerify.verify(signKey, request.getMethod(), request.getRequestURI(),
* request.getHeader("X-Timestamp"), request.getHeader("X-Nonce"), body, request.getHeader("X-Sign"));
*
* 命令行自检(JDK 11+ 可以直接运行源文件):
* java WebhookVerify.java <sign_key> <path> <timestamp> <nonce> <signature> <body_file>
* 验签通过时退出码为 0,否则为 1
*
*/
public final class WebhookVerify {
/** 允许的时间偏差(秒) */
private static final long MAX_SKEW_SECONDS = 300;
private WebhookVerify() {
}
public static boolean verify(String signKey, String method, String path, String timestamp, String nonce, byte[] body, String signature) {
return verify(signKey, method, path, timestamp, nonce, body, signature, System.currentTimeMillis() / 1000);
}
public static boolean verify(String signKey, String method, String path, String timestamp, String nonce, byte[] body,
String signature, long now) {
if (signKey == null || method == null || path == null || timestamp == null || nonce == null || body == null || signature == null) {
return false;
}
if (!timestamp.matches("\\d{1,18}") || Math.abs(now - Long.parseLong(timestamp)) > MAX_SKEW_SECONDS) {
return false; // 时间戳超出 ±5 分钟
}
try {
String bodyHash = hex(MessageDigest.getInstance("SHA-256").digest(body));
String stringToSign = String.join("\n", method.toUpperCase(Locale.ROOT), path, timestamp, nonce, bodyHash);
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(signKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] expected = hex(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8))).getBytes(StandardCharsets.UTF_8);
// MessageDigest.isEqual 是常量时间比较;长度不同(含非 ASCII 字符)直接返回 false
return MessageDigest.isEqual(expected, signature.toLowerCase(Locale.ROOT).getBytes(StandardCharsets.UTF_8));
} catch (GeneralSecurityException | IllegalArgumentException e) {
return false; // 例如 sign_key 为空
}
}
private static String hex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
public static void main(String[] args) throws IOException {
if (args.length != 6) {
System.err.println("用法:java WebhookVerify.java