feat: switch payment callbacks to rsa signatures
This commit is contained in:
1 parent
a75869342c
commit
ad965d086b
4 files changed
+72
-22
No files matched your search
+11
-3
@@ -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<String> 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<String, ?> 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) {
|
||||
|
||||
+21
-5
@@ -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<String, Object> 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<String, Object>();
|
||||
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<String> 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<String> 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<String> response = controller.redirect("merchant-1001", "trade-1001",
|
||||
2, "tx-1001", API_KEY, signature);
|
||||
|
||||
@@ -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;
|
||||
|
||||
+10
-5
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user