api开放钱包创建接口
This commit is contained in:
1 parent
658e6ccf1e
commit
a2be79377b
26 files changed
+636
-4
No files matched your search
@@ -136,6 +136,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
.antMatchers("/life/housingEstate/all-by-letter").permitAll()
|
.antMatchers("/life/housingEstate/all-by-letter").permitAll()
|
||||||
.antMatchers("/system/config/getVerifyStatus").permitAll()
|
.antMatchers("/system/config/getVerifyStatus").permitAll()
|
||||||
.antMatchers("/system/config/setVerifyStatus").permitAll()
|
.antMatchers("/system/config/setVerifyStatus").permitAll()
|
||||||
|
.antMatchers("/api/v1/wallet/**").permitAll()
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
.and()
|
.and()
|
||||||
.headers().frameOptions().disable();
|
.headers().frameOptions().disable();
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import com.ruoyi.system.domain.UsdtOrdersPlus;
|
|||||||
import com.ruoyi.system.service.IAppApiKeysService;
|
import com.ruoyi.system.service.IAppApiKeysService;
|
||||||
import com.ruoyi.system.service.IUsdtOrdersService;
|
import com.ruoyi.system.service.IUsdtOrdersService;
|
||||||
import com.ruoyi.system.service.PaymentSignatureService;
|
import com.ruoyi.system.service.PaymentSignatureService;
|
||||||
|
import com.ruoyi.system.service.AppPrivateKeyCipher;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
@@ -25,13 +26,14 @@ public class PaymentApiController {
|
|||||||
@Autowired private IAppApiKeysService keys;
|
@Autowired private IAppApiKeysService keys;
|
||||||
@Autowired private IUsdtOrdersService orders;
|
@Autowired private IUsdtOrdersService orders;
|
||||||
@Autowired private StringRedisTemplate redis;
|
@Autowired private StringRedisTemplate redis;
|
||||||
|
@Autowired private AppPrivateKeyCipher privateKeyCipher;
|
||||||
|
|
||||||
@PostMapping("/create-transaction")
|
@PostMapping("/create-transaction")
|
||||||
public AjaxResult create(@RequestBody Map<String, Object> body) {
|
public AjaxResult create(@RequestBody Map<String, Object> body) {
|
||||||
String signature = String.valueOf(body.get("signature"));
|
String signature = String.valueOf(body.get("signature"));
|
||||||
Long appId = parseLong(body.get("app_id"));
|
Long appId = parseLong(body.get("app_id"));
|
||||||
AppApiKeysPlus key = activeKey(appId, body.get("api_key"));
|
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"));
|
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 (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("回调地址无效");
|
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")
|
@PostMapping("/query")
|
||||||
public AjaxResult query(@RequestBody Map<String, Object> body) {
|
public AjaxResult query(@RequestBody Map<String, Object> body) {
|
||||||
Long appId = parseLong(body.get("app_id")); AppApiKeysPlus key = activeKey(appId, body.get("api_key")); String signature = String.valueOf(body.get("signature"));
|
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<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getAppId, appId).eq(UsdtOrdersPlus::getOrderId, String.valueOf(body.get("order_id"))));
|
UsdtOrdersPlus order = orders.getOne(new LambdaQueryWrapper<UsdtOrdersPlus>().eq(UsdtOrdersPlus::getAppId, appId).eq(UsdtOrdersPlus::getOrderId, String.valueOf(body.get("order_id"))));
|
||||||
if (order == null) return AjaxResult.error("订单不存在");
|
if (order == null) return AjaxResult.error("订单不存在");
|
||||||
Map<String, Object> result = new HashMap<String, Object>(); 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);
|
Map<String, Object> result = new HashMap<String, Object>(); 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);
|
||||||
|
|||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -21,6 +21,9 @@ public interface AppsMapper extends BaseMapper<AppsPlus>
|
|||||||
/** 查询用户当前未删除的应用数量。 */
|
/** 查询用户当前未删除的应用数量。 */
|
||||||
int countActiveAppsByUserId(@Param("userId") Long userId);
|
int countActiveAppsByUserId(@Param("userId") Long userId);
|
||||||
|
|
||||||
|
/** 锁定应用,串行化同一应用的钱包领取。 */
|
||||||
|
Apps selectAppsByIdForUpdate(@Param("id") Long id);
|
||||||
|
|
||||||
int updateKeyPair(@Param("id") Long id, @Param("publicKey") String publicKey,
|
int updateKeyPair(@Param("id") Long id, @Param("publicKey") String publicKey,
|
||||||
@Param("privateKey") String privateKey, @Param("updatedAt") java.util.Date updatedAt);
|
@Param("privateKey") String privateKey, @Param("updatedAt") java.util.Date updatedAt);
|
||||||
|
|
||||||
|
|||||||
@@ -45,6 +45,18 @@ public interface WalletAddressMapper extends BaseMapper<WalletAddressPlus>
|
|||||||
/** 统计未分配给应用和用户的全局子账号。 */
|
/** 统计未分配给应用和用户的全局子账号。 */
|
||||||
int countGlobalChildAccounts();
|
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);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 修改钱包
|
* 修改钱包
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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() { }
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<String, Long> values = new ConcurrentHashMap<String, Long>();
|
||||||
|
@Override
|
||||||
|
public synchronized boolean reserve(String apiKey, String nonce, long ttlMillis) {
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
for (Map.Entry<String, Long> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.ruoyi.system.security;
|
||||||
|
|
||||||
|
public interface NonceStore {
|
||||||
|
/** 原子保留 nonce;已存在时返回 false。 */
|
||||||
|
boolean reserve(String apiKey, String nonce, long ttlMillis);
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<String, ?> 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<String, ?> params) {
|
||||||
|
SortedMap<String, Object> sorted = new TreeMap<String, Object>();
|
||||||
|
if (params != null) sorted.putAll(params);
|
||||||
|
StringBuilder text = new StringBuilder();
|
||||||
|
for (Map.Entry<String, Object> entry : sorted.entrySet()) {
|
||||||
|
if (entry.getValue() != null && !String.valueOf(entry.getValue()).isEmpty()) {
|
||||||
|
text.append(entry.getKey()).append('=').append(entry.getValue()).append('&');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return text.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<AppApiKeysPlus>()
|
||||||
|
.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("加密请求字段长度超限");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 {
|
private SecretKeySpec encryptionKey() throws Exception {
|
||||||
if (masterKey == null || masterKey.length() < MIN_MASTER_KEY_LENGTH) {
|
if (masterKey == null || masterKey.length() < MIN_MASTER_KEY_LENGTH) {
|
||||||
throw new CustomException("未配置 payment.apps-private-key-encryption-key 或长度不足 32 位");
|
throw new CustomException("未配置 payment.apps-private-key-encryption-key 或长度不足 32 位");
|
||||||
|
|||||||
@@ -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<String, String> values = new HashMap<String, String>();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@ import com.ruoyi.system.mapper.AppsMapper;
|
|||||||
import com.ruoyi.system.domain.Apps;
|
import com.ruoyi.system.domain.Apps;
|
||||||
import com.ruoyi.system.domain.vo.AppApiKeyCreateResult;
|
import com.ruoyi.system.domain.vo.AppApiKeyCreateResult;
|
||||||
import com.ruoyi.system.service.IAppApiKeysService;
|
import com.ruoyi.system.service.IAppApiKeysService;
|
||||||
|
import com.ruoyi.system.service.AppPrivateKeyCipher;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.jdbc.core.JdbcTemplate;
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -39,6 +40,8 @@ public class AppApiKeysServiceImpl extends ServiceImpl<AppApiKeysMapper, AppApiK
|
|||||||
private AppsMapper appsMapper;
|
private AppsMapper appsMapper;
|
||||||
@Autowired
|
@Autowired
|
||||||
private JdbcTemplate jdbcTemplate;
|
private JdbcTemplate jdbcTemplate;
|
||||||
|
@Autowired
|
||||||
|
private AppPrivateKeyCipher privateKeyCipher;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<AppApiKeysPlus> getByIds(List<Long> ids, boolean isUser, SFunction<AppApiKeysPlus, ?>... columns) {
|
public List<AppApiKeysPlus> getByIds(List<Long> ids, boolean isUser, SFunction<AppApiKeysPlus, ?>... columns) {
|
||||||
@@ -237,7 +240,7 @@ public class AppApiKeysServiceImpl extends ServiceImpl<AppApiKeysMapper, AppApiK
|
|||||||
new SecureRandom().nextBytes(keyBytes);
|
new SecureRandom().nextBytes(keyBytes);
|
||||||
String apiKey = "ak_" + Base64.getUrlEncoder().withoutPadding().encodeToString(keyBytes);
|
String apiKey = "ak_" + Base64.getUrlEncoder().withoutPadding().encodeToString(keyBytes);
|
||||||
appApiKeys.setApiKey(apiKey);
|
appApiKeys.setApiKey(apiKey);
|
||||||
appApiKeys.setApiSecret(secret);
|
appApiKeys.setApiSecret(privateKeyCipher.encrypt(secret));
|
||||||
appApiKeys.setUserId(app.getUserId());
|
appApiKeys.setUserId(app.getUserId());
|
||||||
if (appApiKeys.getStatus() == null) appApiKeys.setStatus(1);
|
if (appApiKeys.getStatus() == null) appApiKeys.setStatus(1);
|
||||||
appApiKeys.setCreatedAt(DateUtils.getNowDate());
|
appApiKeys.setCreatedAt(DateUtils.getNowDate());
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.ruoyi.system.domain.UsdtOrdersPlus;
|
|||||||
import com.ruoyi.system.service.IUsdtOrdersService;
|
import com.ruoyi.system.service.IUsdtOrdersService;
|
||||||
import com.ruoyi.system.service.IAppApiKeysService;
|
import com.ruoyi.system.service.IAppApiKeysService;
|
||||||
import com.ruoyi.system.service.PaymentSignatureService;
|
import com.ruoyi.system.service.PaymentSignatureService;
|
||||||
|
import com.ruoyi.system.service.AppPrivateKeyCipher;
|
||||||
import com.ruoyi.system.domain.AppApiKeysPlus;
|
import com.ruoyi.system.domain.AppApiKeysPlus;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.http.*;
|
import org.springframework.http.*;
|
||||||
@@ -18,6 +19,7 @@ import java.util.Date;
|
|||||||
public class PaymentCallbackWorker {
|
public class PaymentCallbackWorker {
|
||||||
@Autowired private IUsdtOrdersService orders;
|
@Autowired private IUsdtOrdersService orders;
|
||||||
@Autowired private IAppApiKeysService keys;
|
@Autowired private IAppApiKeysService keys;
|
||||||
|
@Autowired private AppPrivateKeyCipher privateKeyCipher;
|
||||||
private final RestTemplate http = new RestTemplate();
|
private final RestTemplate http = new RestTemplate();
|
||||||
@Scheduled(fixedDelay = 30000L)
|
@Scheduled(fixedDelay = 30000L)
|
||||||
public void dispatch() {
|
public void dispatch() {
|
||||||
@@ -31,7 +33,7 @@ public class PaymentCallbackWorker {
|
|||||||
.and(wrapper -> wrapper.isNull(AppApiKeysPlus::getExpiredAt).or().gt(AppApiKeysPlus::getExpiredAt, new Date()))
|
.and(wrapper -> wrapper.isNull(AppApiKeysPlus::getExpiredAt).or().gt(AppApiKeysPlus::getExpiredAt, new Date()))
|
||||||
.last("limit 1"));
|
.last("limit 1"));
|
||||||
java.util.Map<String, Object> signatureValues = new java.util.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());
|
java.util.Map<String, Object> signatureValues = new java.util.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", 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());
|
headers.set("X-Payment-Api-Key", key == null ? "" : key.getApiKey());
|
||||||
ResponseEntity<String> response = http.postForEntity(order.getNotifyUrl(), new HttpEntity<String>(body, headers), String.class);
|
ResponseEntity<String> response = http.postForEntity(order.getNotifyUrl(), new HttpEntity<String>(body, headers), String.class);
|
||||||
order.setCallbackNum(order.getCallbackNum() == null ? 1L : order.getCallbackNum() + 1L);
|
order.setCallbackNum(order.getCallbackNum() == null ? 1L : order.getCallbackNum() + 1L);
|
||||||
|
|||||||
@@ -65,6 +65,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
|||||||
where id = #{id} and deleted_at is null
|
where id = #{id} and deleted_at is null
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
<select id="selectAppsByIdForUpdate" resultMap="AppsResult">
|
||||||
|
<include refid="selectAppsVo"/>
|
||||||
|
where id = #{id} and deleted_at is null for update
|
||||||
|
</select>
|
||||||
|
|
||||||
<update id="updateKeyPair">
|
<update id="updateKeyPair">
|
||||||
update apps
|
update apps
|
||||||
set public_key = #{publicKey}, private_key = #{privateKey}, updated_at = #{updatedAt}
|
set public_key = #{publicKey}, private_key = #{privateKey}, updated_at = #{updatedAt}
|
||||||
|
|||||||
@@ -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
|
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
|
and cast(token_index as unsigned) > 0
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
<select id="selectFirstAvailableForUpdate" resultMap="WalletAddressResult">
|
||||||
|
<include refid="selectWalletAddressVo"/>
|
||||||
|
where deleted_at is null and status = 1 and app_id is null and user_id is null
|
||||||
|
and wallet_user_name is null
|
||||||
|
order by id asc limit 1 for update
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select id="selectByAppAndWalletUserName" resultMap="WalletAddressResult">
|
||||||
|
<include refid="selectWalletAddressVo"/>
|
||||||
|
where deleted_at is null and status = 1 and app_id = #{appId}
|
||||||
|
and wallet_user_name = #{walletUserName}
|
||||||
|
order by id asc limit 1
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<update id="bindAvailableWallet">
|
||||||
|
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
|
||||||
|
</update>
|
||||||
|
|
||||||
<insert id="insertWalletAddress" parameterType="WalletAddress" useGeneratedKeys="true" keyProperty="id">
|
<insert id="insertWalletAddress" parameterType="WalletAddress" useGeneratedKeys="true" keyProperty="id">
|
||||||
insert into wallet_address
|
insert into wallet_address
|
||||||
|
|||||||
@@ -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<String, Object> params = new HashMap<String, Object>();
|
||||||
|
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<String, Object> params = new HashMap<String, Object>();
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user