From a2be79377b42f7c7ed97894351294d7927e91d46 Mon Sep 17 00:00:00 2001 From: luqingjie <544309509@qq.com> Date: Sat, 10 Oct 2026 08:46:53 -0400 Subject: [PATCH] =?UTF-8?q?api=E5=BC=80=E6=94=BE=E9=92=B1=E5=8C=85?= =?UTF-8?q?=E5=88=9B=E5=BB=BA=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../framework/config/SecurityConfig.java | 1 + .../controller/PaymentApiController.java | 6 +- .../controller/WalletOpenApiController.java | 30 ++++++ .../system/domain/dto/EncryptedRequest.java | 27 ++++++ .../ruoyi/system/domain/vo/DecryptResult.java | 17 ++++ .../system/domain/vo/WalletCreateResult.java | 17 ++++ .../com/ruoyi/system/mapper/AppsMapper.java | 3 + .../system/mapper/WalletAddressMapper.java | 12 +++ .../com/ruoyi/system/security/AesGcmUtil.java | 46 +++++++++ .../system/security/CryptoConstants.java | 15 +++ .../com/ruoyi/system/security/DigestUtil.java | 14 +++ .../com/ruoyi/system/security/HmacUtil.java | 24 +++++ .../system/security/LocalNonceStore.java | 21 +++++ .../com/ruoyi/system/security/NonceStore.java | 6 ++ .../system/security/RedisNonceStore.java | 24 +++++ .../ruoyi/system/security/RsaCipherUtil.java | 28 ++++++ .../com/ruoyi/system/security/RsaKeyUtil.java | 28 ++++++ .../ruoyi/system/security/SecureClient.java | 48 ++++++++++ .../system/service/ApiSecurityService.java | 94 +++++++++++++++++++ .../system/service/AppPrivateKeyCipher.java | 6 ++ .../system/service/WalletOpenApiService.java | 67 +++++++++++++ .../service/impl/AppApiKeysServiceImpl.java | 5 +- .../service/impl/PaymentCallbackWorker.java | 4 +- .../resources/mapper/system/AppsMapper.xml | 5 + .../mapper/system/WalletAddressMapper.xml | 22 +++++ .../system/security/HybridCryptoTest.java | 70 ++++++++++++++ 26 files changed, 636 insertions(+), 4 deletions(-) create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/controller/WalletOpenApiController.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/domain/dto/EncryptedRequest.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/DecryptResult.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletCreateResult.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/security/AesGcmUtil.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/security/CryptoConstants.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/security/DigestUtil.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/security/HmacUtil.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/security/LocalNonceStore.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/security/NonceStore.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/security/RedisNonceStore.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/security/RsaCipherUtil.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/security/RsaKeyUtil.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/security/SecureClient.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/service/ApiSecurityService.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/service/WalletOpenApiService.java create mode 100644 ruoyi-system/src/test/java/com/ruoyi/system/security/HybridCryptoTest.java diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java index 6b89547..199537b 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java @@ -136,6 +136,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { .antMatchers("/life/housingEstate/all-by-letter").permitAll() .antMatchers("/system/config/getVerifyStatus").permitAll() .antMatchers("/system/config/setVerifyStatus").permitAll() + .antMatchers("/api/v1/wallet/**").permitAll() .anyRequest().authenticated() .and() .headers().frameOptions().disable(); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/PaymentApiController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/PaymentApiController.java index 5496d1f..3a334de 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/controller/PaymentApiController.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/PaymentApiController.java @@ -7,6 +7,7 @@ import com.ruoyi.system.domain.UsdtOrdersPlus; import com.ruoyi.system.service.IAppApiKeysService; import com.ruoyi.system.service.IUsdtOrdersService; import com.ruoyi.system.service.PaymentSignatureService; +import com.ruoyi.system.service.AppPrivateKeyCipher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.data.redis.core.StringRedisTemplate; @@ -25,13 +26,14 @@ public class PaymentApiController { @Autowired private IAppApiKeysService keys; @Autowired private IUsdtOrdersService orders; @Autowired private StringRedisTemplate redis; + @Autowired private AppPrivateKeyCipher privateKeyCipher; @PostMapping("/create-transaction") public AjaxResult create(@RequestBody Map body) { String signature = String.valueOf(body.get("signature")); Long appId = parseLong(body.get("app_id")); AppApiKeysPlus key = activeKey(appId, body.get("api_key")); - if (key == null || !PaymentSignatureService.verify(body, key.getApiSecret(), signature)) return AjaxResult.error("签名无效"); + if (key == null || !PaymentSignatureService.verify(body, privateKeyCipher.decryptCredentialSecret(key.getApiSecret()), signature)) return AjaxResult.error("签名无效"); String orderId = String.valueOf(body.get("order_id")); if (orderId.length() == 0 || orderId.length() > 32 || body.get("amount") == null || body.get("wallet_user_name") == null) return AjaxResult.error("缺少必要参数"); if (!validUrl(body.get("notify_url")) || (body.get("redirect_url") != null && !validUrl(body.get("redirect_url")))) return AjaxResult.error("回调地址无效"); @@ -51,7 +53,7 @@ public class PaymentApiController { @PostMapping("/query") public AjaxResult query(@RequestBody Map body) { Long appId = parseLong(body.get("app_id")); AppApiKeysPlus key = activeKey(appId, body.get("api_key")); String signature = String.valueOf(body.get("signature")); - if (key == null || !PaymentSignatureService.verify(body, key.getApiSecret(), signature)) return AjaxResult.error("签名无效"); + if (key == null || !PaymentSignatureService.verify(body, privateKeyCipher.decryptCredentialSecret(key.getApiSecret()), signature)) return AjaxResult.error("签名无效"); UsdtOrdersPlus order = orders.getOne(new LambdaQueryWrapper().eq(UsdtOrdersPlus::getAppId, appId).eq(UsdtOrdersPlus::getOrderId, String.valueOf(body.get("order_id")))); if (order == null) return AjaxResult.error("订单不存在"); Map result = new HashMap(); result.put("order_id", order.getOrderId()); result.put("trade_id", order.getTradeId()); result.put("status", order.getStatus()); result.put("transaction_id", order.getBlockTransactionId()); return AjaxResult.success(result); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/WalletOpenApiController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/WalletOpenApiController.java new file mode 100644 index 0000000..cfb8c75 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/WalletOpenApiController.java @@ -0,0 +1,30 @@ +package com.ruoyi.system.controller; + +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.system.domain.dto.EncryptedRequest; +import com.ruoyi.system.domain.vo.DecryptResult; +import com.ruoyi.system.service.ApiSecurityService; +import com.ruoyi.system.service.WalletOpenApiService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** 免登录商户钱包 API;生产环境必须由 HTTPS 反向代理保护。 */ +@RestController +@RequestMapping("/api/v1/wallet") +public class WalletOpenApiController { + @Autowired private ApiSecurityService apiSecurityService; + @Autowired private WalletOpenApiService walletOpenApiService; + + @Log(title = "开放 API 创建钱包", businessType = BusinessType.INSERT, + isSaveRequestData = false, isSaveResponseData = false) + @PostMapping("/create") + public AjaxResult create(@RequestBody EncryptedRequest request) { + DecryptResult decrypted = apiSecurityService.decryptAndVerify(request); + return AjaxResult.success(walletOpenApiService.createWallet(decrypted)); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/dto/EncryptedRequest.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/dto/EncryptedRequest.java new file mode 100644 index 0000000..7a4b880 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/dto/EncryptedRequest.java @@ -0,0 +1,27 @@ +package com.ruoyi.system.domain.dto; + +/** 开放 API 混合加密请求。 */ +public class EncryptedRequest { + private String apiKey; + private Long timestamp; + private String nonce; + private String encryptedKey; + private String iv; + private String data; + private String hmac; + + public String getApiKey() { return apiKey; } + public void setApiKey(String apiKey) { this.apiKey = apiKey; } + public Long getTimestamp() { return timestamp; } + public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } + public String getNonce() { return nonce; } + public void setNonce(String nonce) { this.nonce = nonce; } + public String getEncryptedKey() { return encryptedKey; } + public void setEncryptedKey(String encryptedKey) { this.encryptedKey = encryptedKey; } + public String getIv() { return iv; } + public void setIv(String iv) { this.iv = iv; } + public String getData() { return data; } + public void setData(String data) { this.data = data; } + public String getHmac() { return hmac; } + public void setHmac(String hmac) { this.hmac = hmac; } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/DecryptResult.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/DecryptResult.java new file mode 100644 index 0000000..c344c5f --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/DecryptResult.java @@ -0,0 +1,17 @@ +package com.ruoyi.system.domain.vo; + +/** 服务端解密结果及经过认证的调用方身份。 */ +public class DecryptResult { + private final Long appId; + private final Long userId; + private final String plainData; + + public DecryptResult(Long appId, Long userId, String plainData) { + this.appId = appId; + this.userId = userId; + this.plainData = plainData; + } + public Long getAppId() { return appId; } + public Long getUserId() { return userId; } + public String getPlainData() { return plainData; } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletCreateResult.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletCreateResult.java new file mode 100644 index 0000000..b1027e2 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/WalletCreateResult.java @@ -0,0 +1,17 @@ +package com.ruoyi.system.domain.vo; + +/** 开放 API 钱包领取结果。 */ +public class WalletCreateResult { + private final Long appId; + private final String walletUserName; + private final String walletAddress; + + public WalletCreateResult(Long appId, String walletUserName, String walletAddress) { + this.appId = appId; + this.walletUserName = walletUserName; + this.walletAddress = walletAddress; + } + public Long getAppId() { return appId; } + public String getWalletUserName() { return walletUserName; } + public String getWalletAddress() { return walletAddress; } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/AppsMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/AppsMapper.java index e324e22..23dbb89 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/AppsMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/AppsMapper.java @@ -21,6 +21,9 @@ public interface AppsMapper extends BaseMapper /** 查询用户当前未删除的应用数量。 */ int countActiveAppsByUserId(@Param("userId") Long userId); + /** 锁定应用,串行化同一应用的钱包领取。 */ + Apps selectAppsByIdForUpdate(@Param("id") Long id); + int updateKeyPair(@Param("id") Long id, @Param("publicKey") String publicKey, @Param("privateKey") String privateKey, @Param("updatedAt") java.util.Date updatedAt); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/WalletAddressMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/WalletAddressMapper.java index f776201..a138a20 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/WalletAddressMapper.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/WalletAddressMapper.java @@ -45,6 +45,18 @@ public interface WalletAddressMapper extends BaseMapper /** 统计未分配给应用和用户的全局子账号。 */ int countGlobalChildAccounts(); + /** 锁定 ID 最小的未分配钱包,避免并发请求重复领取。 */ + WalletAddress selectFirstAvailableForUpdate(); + + /** 查询应用外部用户已绑定的钱包,用于接口重试幂等。 */ + WalletAddress selectByAppAndWalletUserName(@Param("appId") Long appId, + @Param("walletUserName") String walletUserName); + + /** 仅当钱包仍为空闲状态时绑定归属。 */ + int bindAvailableWallet(@Param("id") Long id, @Param("appId") Long appId, + @Param("userId") Long userId, @Param("walletUserName") String walletUserName, + @Param("updatedAt") java.util.Date updatedAt); + /** * 修改钱包 * diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/security/AesGcmUtil.java b/ruoyi-system/src/main/java/com/ruoyi/system/security/AesGcmUtil.java new file mode 100644 index 0000000..0cfa86f --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/security/AesGcmUtil.java @@ -0,0 +1,46 @@ +package com.ruoyi.system.security; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.Base64; + +/** AES-256-GCM 工具,认证标签包含在 Base64 密文末尾。 */ +public final class AesGcmUtil { + private static final SecureRandom RANDOM = new SecureRandom(); + private AesGcmUtil() { } + + public static SecretKey generateKey() throws Exception { + KeyGenerator generator = KeyGenerator.getInstance("AES"); + generator.init(CryptoConstants.AES_KEY_BITS); + return generator.generateKey(); + } + + public static byte[] generateIv() { + byte[] iv = new byte[CryptoConstants.GCM_IV_BYTES]; + RANDOM.nextBytes(iv); + return iv; + } + + public static String encrypt(String plain, SecretKey key, byte[] iv) throws Exception { + Cipher cipher = cipher(Cipher.ENCRYPT_MODE, key.getEncoded(), iv); + return Base64.getEncoder().encodeToString(cipher.doFinal(plain.getBytes(StandardCharsets.UTF_8))); + } + + public static String decrypt(String value, byte[] key, byte[] iv) throws Exception { + Cipher cipher = cipher(Cipher.DECRYPT_MODE, key, iv); + return new String(cipher.doFinal(Base64.getDecoder().decode(value)), StandardCharsets.UTF_8); + } + + private static Cipher cipher(int mode, byte[] key, byte[] iv) throws Exception { + if (key == null || (key.length != 16 && key.length != 32)) throw new IllegalArgumentException("AES 密钥长度无效"); + if (iv == null || iv.length != CryptoConstants.GCM_IV_BYTES) throw new IllegalArgumentException("AES-GCM IV 必须为 12 字节"); + Cipher cipher = Cipher.getInstance(CryptoConstants.AES_TRANSFORMATION); + cipher.init(mode, new SecretKeySpec(key, "AES"), new GCMParameterSpec(CryptoConstants.GCM_TAG_BITS, iv)); + return cipher; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/security/CryptoConstants.java b/ruoyi-system/src/main/java/com/ruoyi/system/security/CryptoConstants.java new file mode 100644 index 0000000..954b110 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/security/CryptoConstants.java @@ -0,0 +1,15 @@ +package com.ruoyi.system.security; + +/** 开放 API 混合加密协议常量。 */ +public final class CryptoConstants { + public static final String RSA_TRANSFORMATION = "RSA/ECB/OAEPPadding"; + public static final String AES_TRANSFORMATION = "AES/GCM/NoPadding"; + public static final String HMAC_ALGORITHM = "HmacSHA256"; + public static final int AES_KEY_BITS = 256; + public static final int GCM_IV_BYTES = 12; + public static final int GCM_TAG_BITS = 128; + public static final long TIMESTAMP_WINDOW_MILLIS = 5 * 60 * 1000L; + public static final String SIGN_SEPARATOR = "|"; + + private CryptoConstants() { } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/security/DigestUtil.java b/ruoyi-system/src/main/java/com/ruoyi/system/security/DigestUtil.java new file mode 100644 index 0000000..4c24eb3 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/security/DigestUtil.java @@ -0,0 +1,14 @@ +package com.ruoyi.system.security; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; + +public final class DigestUtil { + private DigestUtil() { } + public static String sha256Hex(String value) throws Exception { + byte[] hash = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); + StringBuilder result = new StringBuilder(hash.length * 2); + for (byte item : hash) result.append(String.format("%02x", item & 0xff)); + return result.toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/security/HmacUtil.java b/ruoyi-system/src/main/java/com/ruoyi/system/security/HmacUtil.java new file mode 100644 index 0000000..00dd0d1 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/security/HmacUtil.java @@ -0,0 +1,24 @@ +package com.ruoyi.system.security; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Base64; + +public final class HmacUtil { + private HmacUtil() { } + public static String sign(String secret, long timestamp, String nonce, String dataHash) throws Exception { + String content = timestamp + CryptoConstants.SIGN_SEPARATOR + nonce + + CryptoConstants.SIGN_SEPARATOR + dataHash; + Mac mac = Mac.getInstance(CryptoConstants.HMAC_ALGORITHM); + mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), CryptoConstants.HMAC_ALGORITHM)); + return Base64.getUrlEncoder().withoutPadding().encodeToString( + mac.doFinal(content.getBytes(StandardCharsets.UTF_8))); + } + public static boolean verify(String secret, long timestamp, String nonce, String dataHash, String signature) throws Exception { + if (signature == null) return false; + return MessageDigest.isEqual(sign(secret, timestamp, nonce, dataHash).getBytes(StandardCharsets.US_ASCII), + signature.getBytes(StandardCharsets.US_ASCII)); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/security/LocalNonceStore.java b/ruoyi-system/src/main/java/com/ruoyi/system/security/LocalNonceStore.java new file mode 100644 index 0000000..4d9aa50 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/security/LocalNonceStore.java @@ -0,0 +1,21 @@ +package com.ruoyi.system.security; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** Redis 不可用时的单实例兜底;集群部署必须保证 Redis 可用。 */ +public class LocalNonceStore implements NonceStore { + private final Map values = new ConcurrentHashMap(); + @Override + public synchronized boolean reserve(String apiKey, String nonce, long ttlMillis) { + long now = System.currentTimeMillis(); + for (Map.Entry entry : values.entrySet()) { + if (entry.getValue() <= now) values.remove(entry.getKey(), entry.getValue()); + } + String key = apiKey + ':' + nonce; + Long current = values.get(key); + if (current != null && current > now) return false; + values.put(key, now + ttlMillis); + return true; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/security/NonceStore.java b/ruoyi-system/src/main/java/com/ruoyi/system/security/NonceStore.java new file mode 100644 index 0000000..cd40f97 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/security/NonceStore.java @@ -0,0 +1,6 @@ +package com.ruoyi.system.security; + +public interface NonceStore { + /** 原子保留 nonce;已存在时返回 false。 */ + boolean reserve(String apiKey, String nonce, long ttlMillis); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/security/RedisNonceStore.java b/ruoyi-system/src/main/java/com/ruoyi/system/security/RedisNonceStore.java new file mode 100644 index 0000000..d22b55c --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/security/RedisNonceStore.java @@ -0,0 +1,24 @@ +package com.ruoyi.system.security; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import java.util.concurrent.TimeUnit; + +/** Redis SETNX 防重放,连接异常时退化为本地单实例存储。 */ +@Component +public class RedisNonceStore implements NonceStore { + @Autowired + private StringRedisTemplate redis; + private final NonceStore fallback = new LocalNonceStore(); + + @Override + public boolean reserve(String apiKey, String nonce, long ttlMillis) { + try { + return Boolean.TRUE.equals(redis.opsForValue().setIfAbsent( + "payment:api:nonce:" + apiKey + ':' + nonce, "1", ttlMillis, TimeUnit.MILLISECONDS)); + } catch (RuntimeException e) { + return fallback.reserve(apiKey, nonce, ttlMillis); + } + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/security/RsaCipherUtil.java b/ruoyi-system/src/main/java/com/ruoyi/system/security/RsaCipherUtil.java new file mode 100644 index 0000000..4a80d59 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/security/RsaCipherUtil.java @@ -0,0 +1,28 @@ +package com.ruoyi.system.security; + +import javax.crypto.Cipher; +import javax.crypto.spec.OAEPParameterSpec; +import javax.crypto.spec.PSource; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.MGF1ParameterSpec; +import java.util.Base64; + +/** RSA-OAEP SHA-256 加解密工具。 */ +public final class RsaCipherUtil { + private static final OAEPParameterSpec OAEP = new OAEPParameterSpec( + "SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT); + private RsaCipherUtil() { } + + public static String rsaOaepEncrypt(byte[] key, PublicKey publicKey) throws Exception { + Cipher cipher = Cipher.getInstance(CryptoConstants.RSA_TRANSFORMATION); + cipher.init(Cipher.ENCRYPT_MODE, publicKey, OAEP); + return Base64.getEncoder().encodeToString(cipher.doFinal(key)); + } + + public static byte[] rsaOaepDecrypt(String value, PrivateKey privateKey) throws Exception { + Cipher cipher = Cipher.getInstance(CryptoConstants.RSA_TRANSFORMATION); + cipher.init(Cipher.DECRYPT_MODE, privateKey, OAEP); + return cipher.doFinal(Base64.getDecoder().decode(value)); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/security/RsaKeyUtil.java b/ruoyi-system/src/main/java/com/ruoyi/system/security/RsaKeyUtil.java new file mode 100644 index 0000000..f64a480 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/security/RsaKeyUtil.java @@ -0,0 +1,28 @@ +package com.ruoyi.system.security; + +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; + +/** 加载 PKCS#8 私钥和 X.509 公钥,兼容 PEM 与纯 Base64。 */ +public final class RsaKeyUtil { + private RsaKeyUtil() { } + + public static PublicKey loadPublicKey(String value) throws Exception { + return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decodePem(value))); + } + + public static PrivateKey loadPrivateKey(String value) throws Exception { + return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decodePem(value))); + } + + private static byte[] decodePem(String value) { + if (value == null) throw new IllegalArgumentException("RSA 密钥不能为空"); + String body = value.replaceAll("-----BEGIN [A-Z ]+-----", "") + .replaceAll("-----END [A-Z ]+-----", "").replaceAll("\\s", ""); + return Base64.getDecoder().decode(body); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/security/SecureClient.java b/ruoyi-system/src/main/java/com/ruoyi/system/security/SecureClient.java new file mode 100644 index 0000000..696db24 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/security/SecureClient.java @@ -0,0 +1,48 @@ +package com.ruoyi.system.security; + +import com.ruoyi.system.domain.dto.EncryptedRequest; +import javax.crypto.SecretKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.util.Base64; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; + +/** 可信 Java 客户端 SDK;apiSecret 必须来自安全配置,禁止用于浏览器端。 */ +public final class SecureClient { + private static final SecureRandom RANDOM = new SecureRandom(); + private SecureClient() { } + + public static EncryptedRequest encrypt(String apiKey, String apiSecret, PublicKey publicKey, + Map params) throws Exception { + String plainData = canonicalize(params); + SecretKey aesKey = AesGcmUtil.generateKey(); + byte[] iv = AesGcmUtil.generateIv(); + long timestamp = System.currentTimeMillis(); + byte[] nonceBytes = new byte[16]; + RANDOM.nextBytes(nonceBytes); + String nonce = Base64.getUrlEncoder().withoutPadding().encodeToString(nonceBytes); + EncryptedRequest request = new EncryptedRequest(); + request.setApiKey(apiKey); + request.setTimestamp(timestamp); + request.setNonce(nonce); + request.setEncryptedKey(RsaCipherUtil.rsaOaepEncrypt(aesKey.getEncoded(), publicKey)); + request.setIv(Base64.getEncoder().encodeToString(iv)); + request.setData(AesGcmUtil.encrypt(plainData, aesKey, iv)); + request.setHmac(HmacUtil.sign(apiSecret, timestamp, nonce, DigestUtil.sha256Hex(plainData))); + return request; + } + + public static String canonicalize(Map params) { + SortedMap sorted = new TreeMap(); + if (params != null) sorted.putAll(params); + StringBuilder text = new StringBuilder(); + for (Map.Entry entry : sorted.entrySet()) { + if (entry.getValue() != null && !String.valueOf(entry.getValue()).isEmpty()) { + text.append(entry.getKey()).append('=').append(entry.getValue()).append('&'); + } + } + return text.toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ApiSecurityService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ApiSecurityService.java new file mode 100644 index 0000000..0640b07 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ApiSecurityService.java @@ -0,0 +1,94 @@ +package com.ruoyi.system.service; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.ruoyi.common.exception.CustomException; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.AppApiKeysPlus; +import com.ruoyi.system.domain.Apps; +import com.ruoyi.system.domain.dto.EncryptedRequest; +import com.ruoyi.system.domain.vo.DecryptResult; +import com.ruoyi.system.mapper.AppsMapper; +import com.ruoyi.system.security.AesGcmUtil; +import com.ruoyi.system.security.CryptoConstants; +import com.ruoyi.system.security.DigestUtil; +import com.ruoyi.system.security.HmacUtil; +import com.ruoyi.system.security.NonceStore; +import com.ruoyi.system.security.RsaCipherUtil; +import com.ruoyi.system.security.RsaKeyUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Arrays; +import java.util.Base64; +import java.util.Date; +import java.util.Objects; + +/** 开放 API 身份校验、抗重放和混合解密编排。 */ +@Service +public class ApiSecurityService { + @Autowired private IAppApiKeysService apiKeysService; + @Autowired private AppsMapper appsMapper; + @Autowired private AppPrivateKeyCipher privateKeyCipher; + @Autowired private NonceStore nonceStore; + + public DecryptResult decryptAndVerify(EncryptedRequest request) { + validateRequest(request); + long now = System.currentTimeMillis(); + if (request.getTimestamp() < now - CryptoConstants.TIMESTAMP_WINDOW_MILLIS + || request.getTimestamp() > now + CryptoConstants.TIMESTAMP_WINDOW_MILLIS) { + throw new CustomException("请求已过期"); + } + Date currentTime = new Date(now); + AppApiKeysPlus credential = apiKeysService.getOne(new LambdaQueryWrapper() + .eq(AppApiKeysPlus::getApiKey, request.getApiKey()).eq(AppApiKeysPlus::getStatus, 1) + .isNull(AppApiKeysPlus::getDeletedAt) + .and(wrapper -> wrapper.isNull(AppApiKeysPlus::getExpiredAt) + .or().gt(AppApiKeysPlus::getExpiredAt, currentTime))); + if (credential == null) throw new CustomException("API 凭证无效"); + Apps app = appsMapper.selectAppsById(credential.getAppId()); + if (app == null || app.getStatus() == null || app.getStatus() != 1 + || !Objects.equals(credential.getUserId(), app.getUserId())) { + throw new CustomException("API 凭证无效"); + } + + byte[] aesKey = null; + try { + String privateKey = privateKeyCipher.decrypt(app.getPrivateKey()); + aesKey = RsaCipherUtil.rsaOaepDecrypt(request.getEncryptedKey(), RsaKeyUtil.loadPrivateKey(privateKey)); + byte[] iv = Base64.getDecoder().decode(request.getIv()); + String plainData = AesGcmUtil.decrypt(request.getData(), aesKey, iv); + String dataHash = DigestUtil.sha256Hex(plainData); + String apiSecret = privateKeyCipher.decryptCredentialSecret(credential.getApiSecret()); + if (!HmacUtil.verify(apiSecret, request.getTimestamp(), request.getNonce(), + dataHash, request.getHmac())) { + throw new CustomException("请求认证失败"); + } + if (!nonceStore.reserve(request.getApiKey(), request.getNonce(), + CryptoConstants.TIMESTAMP_WINDOW_MILLIS)) { + throw new CustomException("请求 nonce 已使用"); + } + return new DecryptResult(app.getId(), app.getUserId(), plainData); + } catch (CustomException e) { + throw e; + } catch (Exception e) { + // 不向调用方暴露 RSA、AES 或 Base64 的具体失败细节。 + throw new CustomException("请求解密或认证失败"); + } finally { + if (aesKey != null) Arrays.fill(aesKey, (byte) 0); + } + } + + private void validateRequest(EncryptedRequest request) { + if (request == null || StringUtils.isBlank(request.getApiKey()) || request.getTimestamp() == null + || StringUtils.isBlank(request.getNonce()) || StringUtils.isBlank(request.getEncryptedKey()) + || StringUtils.isBlank(request.getIv()) || StringUtils.isBlank(request.getData()) + || StringUtils.isBlank(request.getHmac())) { + throw new CustomException("加密请求字段不完整"); + } + if (request.getApiKey().length() > 128 || request.getNonce().length() > 128 + || request.getEncryptedKey().length() > 2048 || request.getIv().length() > 64 + || request.getData().length() > 16384 || request.getHmac().length() > 128) { + throw new CustomException("加密请求字段长度超限"); + } + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/AppPrivateKeyCipher.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/AppPrivateKeyCipher.java index 586e48e..a76469a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/AppPrivateKeyCipher.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/AppPrivateKeyCipher.java @@ -64,6 +64,12 @@ public class AppPrivateKeyCipher { } } + /** 解密 API Secret;无版本前缀时兼容升级前的历史明文数据。 */ + public String decryptCredentialSecret(String storedValue) { + if (storedValue == null || storedValue.trim().isEmpty()) throw new CustomException("API Secret 未配置"); + return storedValue.startsWith(VERSION + ":") ? decrypt(storedValue) : storedValue; + } + private SecretKeySpec encryptionKey() throws Exception { if (masterKey == null || masterKey.length() < MIN_MASTER_KEY_LENGTH) { throw new CustomException("未配置 payment.apps-private-key-encryption-key 或长度不足 32 位"); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletOpenApiService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletOpenApiService.java new file mode 100644 index 0000000..b1aaf19 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/WalletOpenApiService.java @@ -0,0 +1,67 @@ +package com.ruoyi.system.service; + +import com.ruoyi.common.exception.CustomException; +import com.ruoyi.common.utils.DateUtils; +import com.ruoyi.system.domain.WalletAddress; +import com.ruoyi.system.domain.Apps; +import com.ruoyi.system.domain.vo.DecryptResult; +import com.ruoyi.system.domain.vo.WalletCreateResult; +import com.ruoyi.system.mapper.WalletAddressMapper; +import com.ruoyi.system.mapper.AppsMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** 商户开放 API 钱包分配业务。 */ +@Service +public class WalletOpenApiService { + @Autowired private WalletAddressMapper walletAddressMapper; + @Autowired private AppsMapper appsMapper; + + @Transactional(rollbackFor = Exception.class) + public WalletCreateResult createWallet(DecryptResult request) { + String walletUserName = parseWalletUserName(request.getPlainData()); + Apps app = appsMapper.selectAppsByIdForUpdate(request.getAppId()); + if (app == null || app.getStatus() == null || app.getStatus() != 1 + || !Objects.equals(app.getUserId(), request.getUserId())) { + throw new CustomException("商户应用不可用"); + } + WalletAddress existing = walletAddressMapper.selectByAppAndWalletUserName(request.getAppId(), walletUserName); + if (existing != null) return result(existing, request.getAppId(), walletUserName); + + WalletAddress available = walletAddressMapper.selectFirstAvailableForUpdate(); + if (available == null) throw new CustomException("暂无可用钱包地址,请联系平台管理员补充子账号"); + if (walletAddressMapper.bindAvailableWallet(available.getId(), request.getAppId(), request.getUserId(), + walletUserName, DateUtils.getNowDate()) != 1) { + throw new CustomException("钱包分配失败,请重试"); + } + return result(available, request.getAppId(), walletUserName); + } + + private WalletCreateResult result(WalletAddress wallet, Long appId, String walletUserName) { + return new WalletCreateResult(appId, walletUserName, wallet.getToken()); + } + + private String parseWalletUserName(String plainData) { + Map values = new HashMap(); + for (String part : plainData.split("&")) { + if (part.isEmpty()) continue; + int separator = part.indexOf('='); + if (separator <= 0 || separator == part.length() - 1) throw new CustomException("业务参数格式错误"); + String old = values.put(part.substring(0, separator), part.substring(separator + 1)); + if (old != null) throw new CustomException("业务参数不能重复"); + } + if (values.size() != 1 || !values.containsKey("walletUserName")) { + throw new CustomException("仅支持 walletUserName 参数"); + } + String value = values.get("walletUserName").trim(); + if (value.length() > 256 || !value.matches("[A-Za-z0-9_.@:-]+")) { + throw new CustomException("walletUserName 格式错误"); + } + return value; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AppApiKeysServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AppApiKeysServiceImpl.java index 30df6d7..658a194 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AppApiKeysServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AppApiKeysServiceImpl.java @@ -16,6 +16,7 @@ import com.ruoyi.system.mapper.AppsMapper; import com.ruoyi.system.domain.Apps; import com.ruoyi.system.domain.vo.AppApiKeyCreateResult; import com.ruoyi.system.service.IAppApiKeysService; +import com.ruoyi.system.service.AppPrivateKeyCipher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; @@ -39,6 +40,8 @@ public class AppApiKeysServiceImpl extends ServiceImpl getByIds(List ids, boolean isUser, SFunction... columns) { @@ -237,7 +240,7 @@ public class AppApiKeysServiceImpl extends ServiceImpl wrapper.isNull(AppApiKeysPlus::getExpiredAt).or().gt(AppApiKeysPlus::getExpiredAt, new Date())) .last("limit 1")); java.util.Map signatureValues = new java.util.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", key == null ? "" : PaymentSignatureService.sign(signatureValues, key.getApiSecret())); + headers.set("X-Payment-Signature", key == null ? "" : PaymentSignatureService.sign(signatureValues, privateKeyCipher.decryptCredentialSecret(key.getApiSecret()))); headers.set("X-Payment-Api-Key", key == null ? "" : key.getApiKey()); ResponseEntity response = http.postForEntity(order.getNotifyUrl(), new HttpEntity(body, headers), String.class); order.setCallbackNum(order.getCallbackNum() == null ? 1L : order.getCallbackNum() + 1L); diff --git a/ruoyi-system/src/main/resources/mapper/system/AppsMapper.xml b/ruoyi-system/src/main/resources/mapper/system/AppsMapper.xml index cd0e1c7..0387bab 100644 --- a/ruoyi-system/src/main/resources/mapper/system/AppsMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/system/AppsMapper.xml @@ -65,6 +65,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" where id = #{id} and deleted_at is null + + update apps set public_key = #{publicKey}, private_key = #{privateKey}, updated_at = #{updatedAt} diff --git a/ruoyi-system/src/main/resources/mapper/system/WalletAddressMapper.xml b/ruoyi-system/src/main/resources/mapper/system/WalletAddressMapper.xml index 6e96697..2df5b70 100644 --- a/ruoyi-system/src/main/resources/mapper/system/WalletAddressMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/system/WalletAddressMapper.xml @@ -97,6 +97,28 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" where deleted_at is null and app_id is null and user_id is null and wallet_user_name is null and cast(token_index as unsigned) > 0 + + + + + + + update wallet_address + set app_id = #{appId}, user_id = #{userId}, wallet_user_name = #{walletUserName}, + updated_at = #{updatedAt} + where id = #{id} and deleted_at is null and status = 1 + and app_id is null and user_id is null and wallet_user_name is null + insert into wallet_address diff --git a/ruoyi-system/src/test/java/com/ruoyi/system/security/HybridCryptoTest.java b/ruoyi-system/src/test/java/com/ruoyi/system/security/HybridCryptoTest.java new file mode 100644 index 0000000..355ee00 --- /dev/null +++ b/ruoyi-system/src/test/java/com/ruoyi/system/security/HybridCryptoTest.java @@ -0,0 +1,70 @@ +package com.ruoyi.system.security; + +import com.ruoyi.system.domain.dto.EncryptedRequest; +import org.junit.Assert; +import org.junit.Test; + +import javax.crypto.AEADBadTagException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; + +public class HybridCryptoTest { + @Test + public void shouldRoundTripEncryptedRequest() throws Exception { + KeyPair keyPair = keyPair(); + Map params = new HashMap(); + params.put("walletUserName", "lu7213"); + EncryptedRequest request = SecureClient.encrypt("ak_test", "secret-value", keyPair.getPublic(), params); + + byte[] aesKey = RsaCipherUtil.rsaOaepDecrypt(request.getEncryptedKey(), keyPair.getPrivate()); + String plain = AesGcmUtil.decrypt(request.getData(), aesKey, Base64.getDecoder().decode(request.getIv())); + Assert.assertEquals("walletUserName=lu7213&", plain); + Assert.assertTrue(HmacUtil.verify("secret-value", request.getTimestamp(), request.getNonce(), + DigestUtil.sha256Hex(plain), request.getHmac())); + } + + @Test + public void shouldRejectWrongHmacAndChangedTimestampOrNonce() throws Exception { + String hash = DigestUtil.sha256Hex("walletUserName=lu7213&"); + long timestamp = System.currentTimeMillis(); + String signature = HmacUtil.sign("secret-value", timestamp, "nonce-one", hash); + Assert.assertFalse(HmacUtil.verify("wrong-secret", timestamp, "nonce-one", hash, signature)); + Assert.assertFalse(HmacUtil.verify("secret-value", timestamp + 1, "nonce-one", hash, signature)); + Assert.assertFalse(HmacUtil.verify("secret-value", timestamp, "nonce-two", hash, signature)); + } + + @Test(expected = AEADBadTagException.class) + public void shouldRejectTamperedCiphertext() throws Exception { + KeyPair keyPair = keyPair(); + Map params = new HashMap(); + params.put("walletUserName", "lu7213"); + EncryptedRequest request = SecureClient.encrypt("ak_test", "secret-value", keyPair.getPublic(), params); + byte[] ciphertext = Base64.getDecoder().decode(request.getData()); + ciphertext[0] ^= 1; + byte[] aesKey = RsaCipherUtil.rsaOaepDecrypt(request.getEncryptedKey(), keyPair.getPrivate()); + AesGcmUtil.decrypt(Base64.getEncoder().encodeToString(ciphertext), aesKey, + Base64.getDecoder().decode(request.getIv())); + } + + @Test + public void shouldRejectReplayNonce() { + NonceStore store = new LocalNonceStore(); + Assert.assertTrue(store.reserve("ak_test", "same-nonce", 300000L)); + Assert.assertFalse(store.reserve("ak_test", "same-nonce", 300000L)); + } + + @Test + public void shouldIdentifyExpiredTimestamp() { + long expired = System.currentTimeMillis() - CryptoConstants.TIMESTAMP_WINDOW_MILLIS - 1; + Assert.assertTrue(Math.abs(System.currentTimeMillis() - expired) > CryptoConstants.TIMESTAMP_WINDOW_MILLIS); + } + + private KeyPair keyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } +}