feat: switch payment callbacks to rsa signatures

This commit is contained in:
lu7213 committed 2026-10-15 04:37:41 -04:00
1 parent a75869342c
commit ad965d086b
4 files changed
+72 -22

No files matched your search

@@ -6,29 +6,50 @@ import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Base64;
/** 支付 API 签名:按键排序拼接非空参数后使用 secret 计算 HMAC-SHA256。 */
public final class PaymentSignatureService {
private PaymentSignatureService() { }
public static String sign(Map<String, ?> values, String secret) {
TreeMap<String, Object> sorted = new TreeMap<String, Object>(values);
StringBuilder text = new StringBuilder();
for (Map.Entry<String, Object> entry : sorted.entrySet()) {
if (entry.getValue() != null && !"".equals(String.valueOf(entry.getValue())) && !"signature".equals(entry.getKey())) {
if (text.length() > 0) text.append('&');
text.append(entry.getKey()).append('=').append(entry.getValue());
}
}
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
byte[] digest = mac.doFinal(text.toString().getBytes("UTF-8"));
byte[] digest = mac.doFinal(canonicalText(values).getBytes("UTF-8"));
StringBuilder result = new StringBuilder();
for (byte b : digest) result.append(String.format("%02x", b & 0xff));
return result.toString();
} catch (Exception ex) { throw new IllegalStateException("HMAC-SHA256 unavailable", ex); }
}
/** 使用应用 RSA 私钥对同一份规范化回调内容签名。 */
public static String signRsa(Map<String, ?> values, PrivateKey privateKey) {
try {
Signature signer = Signature.getInstance("SHA256withRSA");
signer.initSign(privateKey);
signer.update(canonicalText(values).getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(signer.sign());
} catch (Exception ex) {
throw new IllegalStateException("RSA-SHA256 unavailable", ex);
}
}
/** 回调签名的稳定文本格式:键名升序,忽略空值。 */
public static String canonicalText(Map<String, ?> values) {
TreeMap<String, Object> sorted = new TreeMap<String, Object>(values);
StringBuilder text = new StringBuilder();
for (Map.Entry<String, Object> entry : sorted.entrySet()) {
if (entry.getValue() != null && !"".equals(String.valueOf(entry.getValue()))
&& !"signature".equals(entry.getKey())) {
if (text.length() > 0) text.append('&');
text.append(entry.getKey()).append('=').append(entry.getValue());
}
}
return text.toString();
}
/** 使用常量时间比较签名,避免普通字符串比较泄露匹配前缀信息。 */
public static boolean verify(Map<String, ?> values, String secret, String signature) {
if (secret == null || signature == null) return false;
@@ -6,6 +6,9 @@ import com.ruoyi.system.service.IUsdtOrdersService;
import com.ruoyi.system.service.IAppApiKeysService;
import com.ruoyi.system.service.PaymentSignatureService;
import com.ruoyi.system.service.AppPrivateKeyCipher;
import com.ruoyi.system.service.IAppsService;
import com.ruoyi.system.domain.AppsPlus;
import com.ruoyi.system.security.RsaKeyUtil;
import com.ruoyi.system.domain.AppApiKeysPlus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
@@ -19,6 +22,7 @@ import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;
import java.security.PrivateKey;
/** 回调只在对方响应正文严格为 ok 时确认,失败保留未确认状态并重试。 */
@Component
@@ -27,6 +31,7 @@ public class PaymentCallbackWorker {
@Autowired private IUsdtOrdersService orders;
@Autowired private IAppApiKeysService keys;
@Autowired private AppPrivateKeyCipher privateKeyCipher;
@Autowired private IAppsService appsService;
private final RestTemplate http;
public PaymentCallbackWorker() {
@@ -50,16 +55,16 @@ public class PaymentCallbackWorker {
.eq(AppApiKeysPlus::getStatus, 1).isNull(AppApiKeysPlus::getDeletedAt)
.and(wrapper -> wrapper.isNull(AppApiKeysPlus::getExpiredAt).or().gt(AppApiKeysPlus::getExpiredAt, new Date()))
.last("limit 1"));
if (key == null || key.getApiKey() == null || key.getApiSecret() == null) {
throw new IllegalStateException("订单所属应用没有有效回调密钥");
}
if (key == null || key.getApiKey() == null) throw new IllegalStateException("订单所属应用没有有效API Key");
AppsPlus app = appsService.getById(order.getAppId());
if (app == null || app.getPrivateKey() == null) throw new IllegalStateException("订单所属应用没有有效RSA私钥");
PrivateKey privateKey = RsaKeyUtil.loadPrivateKey(privateKeyCipher.decrypt(app.getPrivateKey()));
Map<String, Object> signatureValues = new HashMap<String, Object>();
signatureValues.put("order_id", order.getOrderId());
signatureValues.put("trade_id", order.getTradeId());
signatureValues.put("status", order.getStatus());
signatureValues.put("transaction_id", order.getBlockTransactionId());
headers.set("X-Payment-Signature", PaymentSignatureService.sign(signatureValues,
privateKeyCipher.decryptCredentialSecret(key.getApiSecret())));
headers.set("X-Payment-Rsa-Signature", PaymentSignatureService.signRsa(signatureValues, privateKey));
headers.set("X-Payment-Api-Key", key.getApiKey());
ResponseEntity<String> response = http.postForEntity(order.getNotifyUrl(),
new HttpEntity<String>(JSON.toJSONString(signatureValues), headers), String.class);