api开放钱包创建接口
This commit is contained in:
1 parent
658e6ccf1e
commit
a2be79377b
26 files changed
+636
-4
No files matched your search
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user