From ad965d086b4c969e056aa3470426ddf358185c3b Mon Sep 17 00:00:00 2001 From: luqingjie <544309509@qq.com> Date: Thu, 15 Oct 2026 04:37:41 -0400 Subject: [PATCH] feat: switch payment callbacks to rsa signatures --- .../system/SysUsdtDemoController.java | 14 +++++-- .../system/SysUsdtDemoControllerTest.java | 26 ++++++++++--- .../service/PaymentSignatureService.java | 39 ++++++++++++++----- .../service/impl/PaymentCallbackWorker.java | 15 ++++--- 4 files changed, 72 insertions(+), 22 deletions(-) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUsdtDemoController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUsdtDemoController.java index 83e79b9..c93b180 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUsdtDemoController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUsdtDemoController.java @@ -35,6 +35,8 @@ import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.PublicKey; +import java.security.Signature; +import java.util.Base64; import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -62,7 +64,7 @@ public class SysUsdtDemoController { @PostMapping("/notify") public ResponseEntity notify( @RequestHeader(value = "X-Payment-Api-Key", required = false) String apiKey, - @RequestHeader(value = "X-Payment-Signature", required = false) String signature, + @RequestHeader(value = "X-Payment-Rsa-Signature", required = false) String signature, @RequestBody(required = false) String body) { try { JSONObject payload = parseCallbackPayload(body); @@ -224,10 +226,16 @@ public class SysUsdtDemoController { /** API Key和签名均使用常量时间比较,避免泄露匹配前缀。 */ private boolean verifyCallback(Map values, String apiKey, String signature) { String expectedApiKey = requiredEnvWithAlias("PAYMENT_API_KEY", "PAYMENT_API_KEK"); - if (!constantTimeEquals(expectedApiKey, apiKey)) { + if (!constantTimeEquals(expectedApiKey, apiKey) || StringUtils.isBlank(signature)) return false; + try { + PublicKey publicKey = RsaKeyUtil.loadPublicKey(requiredEnv("PAYMENT_CALLBACK_PUBLIC_KEY").replace("\\n", "\n")); + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(publicKey); + verifier.update(PaymentSignatureService.canonicalText(values).getBytes(StandardCharsets.UTF_8)); + return verifier.verify(Base64.getDecoder().decode(signature)); + } catch (Exception ex) { return false; } - return PaymentSignatureService.verify(values, requiredEnv("PAYMENT_API_SECRET"), signature); } private boolean constantTimeEquals(String expected, String actual) { diff --git a/ruoyi-admin/src/test/java/com/ruoyi/web/controller/system/SysUsdtDemoControllerTest.java b/ruoyi-admin/src/test/java/com/ruoyi/web/controller/system/SysUsdtDemoControllerTest.java index 598eeb3..5d4811a 100644 --- a/ruoyi-admin/src/test/java/com/ruoyi/web/controller/system/SysUsdtDemoControllerTest.java +++ b/ruoyi-admin/src/test/java/com/ruoyi/web/controller/system/SysUsdtDemoControllerTest.java @@ -9,21 +9,34 @@ import org.springframework.http.ResponseEntity; import java.util.HashMap; import java.util.Map; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.util.Base64; import static org.junit.Assert.assertEquals; public class SysUsdtDemoControllerTest { private static final String API_KEY = "demo-api-key"; - private static final String API_SECRET = "demo-api-secret-value"; + private static final String API_SECRET = "unused-rsa-migration-value"; private SysUsdtDemoController controller; private Map values; + private PrivateKey privateKey; @Before public void setUp() { + try { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair pair = generator.generateKeyPair(); + privateKey = pair.getPrivate(); + final String publicKey = "-----BEGIN PUBLIC KEY-----\n" + + Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()) + + "\n-----END PUBLIC KEY-----"; controller = new SysUsdtDemoController() { @Override protected String requiredEnv(String name) { - return API_SECRET; + return publicKey; } @Override @@ -31,6 +44,9 @@ public class SysUsdtDemoControllerTest { return API_KEY; } }; + } catch (Exception ex) { + throw new IllegalStateException(ex); + } values = new HashMap(); values.put("order_id", "merchant-1001"); values.put("trade_id", "trade-1001"); @@ -40,7 +56,7 @@ public class SysUsdtDemoControllerTest { @Test public void notifyShouldAcceptValidSignature() { - String signature = PaymentSignatureService.sign(values, API_SECRET); + String signature = PaymentSignatureService.signRsa(values, privateKey); ResponseEntity response = controller.notify(API_KEY, signature, JSON.toJSONString(values)); @@ -60,7 +76,7 @@ public class SysUsdtDemoControllerTest { @Test public void notifyShouldRejectWrongApiKey() { - String signature = PaymentSignatureService.sign(values, API_SECRET); + String signature = PaymentSignatureService.signRsa(values, privateKey); ResponseEntity response = controller.notify("wrong-key", signature, JSON.toJSONString(values)); @@ -70,7 +86,7 @@ public class SysUsdtDemoControllerTest { @Test public void redirectShouldAcceptValidSignature() { - String signature = PaymentSignatureService.sign(values, API_SECRET); + String signature = PaymentSignatureService.signRsa(values, privateKey); ResponseEntity response = controller.redirect("merchant-1001", "trade-1001", 2, "tx-1001", API_KEY, signature); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/PaymentSignatureService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/PaymentSignatureService.java index df4b21e..a546a4a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/PaymentSignatureService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/PaymentSignatureService.java @@ -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 values, String secret) { - TreeMap sorted = new TreeMap(values); - StringBuilder text = new StringBuilder(); - for (Map.Entry 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 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 values) { + TreeMap sorted = new TreeMap(values); + StringBuilder text = new StringBuilder(); + for (Map.Entry 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 values, String secret, String signature) { if (secret == null || signature == null) return false; diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/PaymentCallbackWorker.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/PaymentCallbackWorker.java index ccd2bb1..47eb0a4 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/PaymentCallbackWorker.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/PaymentCallbackWorker.java @@ -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 signatureValues = new HashMap(); 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 response = http.postForEntity(order.getNotifyUrl(), new HttpEntity(JSON.toJSONString(signatureValues), headers), String.class);