apps添加私钥
This commit is contained in:
1 parent
051f78b59c
commit
35c7bcc8aa
10 files changed
+152
-79
No files matched your search
@@ -11,7 +11,6 @@ import com.ruoyi.common.utils.poi.ExcelUtil;
|
||||
import com.ruoyi.system.domain.Apps;
|
||||
import com.ruoyi.system.domain.AppsPlus;
|
||||
import com.ruoyi.system.service.IAppsService;
|
||||
import com.ruoyi.system.domain.dto.AppPublicKeyRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -44,44 +43,22 @@ public class AppsController extends BaseController {
|
||||
return AjaxResult.success(appsService.getGlobalAggregationAddress());
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 RSA 密钥对。私钥只在本次响应中返回,因此禁止操作日志保存响应体。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('system:apps:add')")
|
||||
@Log(title = "生成商户 RSA 密钥对", businessType = BusinessType.OTHER,
|
||||
isSaveRequestData = false, isSaveResponseData = false)
|
||||
@PostMapping("/generate-key-pair")
|
||||
public AjaxResult generateKeyPair() {
|
||||
return AjaxResult.success(appsService.generateKeyPair());
|
||||
}
|
||||
|
||||
/** 商户端生成 RSA 密钥对,私钥同样不保存。 */
|
||||
@PreAuthorize("@ss.hasPermi('system:apps:user-add')")
|
||||
@Log(title = "商户生成 RSA 密钥对", businessType = BusinessType.OTHER,
|
||||
isSaveRequestData = false, isSaveResponseData = false)
|
||||
@PostMapping("/user/generate-key-pair")
|
||||
public AjaxResult userGenerateKeyPair() {
|
||||
return AjaxResult.success(appsService.generateKeyPair());
|
||||
}
|
||||
|
||||
/** 单独设置商户公钥。 */
|
||||
/** 由系统轮换商户 RSA 密钥对,私钥加密保存且不返回。 */
|
||||
@PreAuthorize("@ss.hasPermi('system:apps:edit')")
|
||||
@Log(title = "设置商户公钥", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/{id}/public-key")
|
||||
public AjaxResult updatePublicKey(@PathVariable("id") Long id,
|
||||
@RequestBody AppPublicKeyRequest request) {
|
||||
return toAjax(appsService.updatePublicKey(id,
|
||||
request == null ? null : request.getPublicKey(), false));
|
||||
@Log(title = "轮换商户 RSA 密钥对", businessType = BusinessType.UPDATE,
|
||||
isSaveRequestData = false, isSaveResponseData = false)
|
||||
@PutMapping("/{id}/key-pair")
|
||||
public AjaxResult rotateKeyPair(@PathVariable("id") Long id) {
|
||||
return toAjax(appsService.rotateKeyPair(id, false));
|
||||
}
|
||||
|
||||
/** 商户端单独设置自己的公钥。 */
|
||||
/** 商户端轮换自己的 RSA 密钥对。 */
|
||||
@PreAuthorize("@ss.hasPermi('system:apps:user-edit')")
|
||||
@Log(title = "商户设置公钥", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/user/{id}/public-key")
|
||||
public AjaxResult userUpdatePublicKey(@PathVariable("id") Long id,
|
||||
@RequestBody AppPublicKeyRequest request) {
|
||||
return toAjax(appsService.updatePublicKey(id,
|
||||
request == null ? null : request.getPublicKey(), true));
|
||||
@Log(title = "商户轮换 RSA 密钥对", businessType = BusinessType.UPDATE,
|
||||
isSaveRequestData = false, isSaveResponseData = false)
|
||||
@PutMapping("/user/{id}/key-pair")
|
||||
public AjaxResult userRotateKeyPair(@PathVariable("id") Long id) {
|
||||
return toAjax(appsService.rotateKeyPair(id, true));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('system:apps:getByIds')")
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.ruoyi.system.domain;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import com.ruoyi.common.annotation.Excel;
|
||||
@@ -64,6 +65,10 @@ public class Apps extends BaseEntity
|
||||
@Excel(name = "公钥")
|
||||
private String publicKey;
|
||||
|
||||
/** 加密后的私钥,禁止序列化到接口响应 */
|
||||
@JsonIgnore
|
||||
private String privateKey;
|
||||
|
||||
/** 信用额度 */
|
||||
@Excel(name = "信用额度金额")
|
||||
private BigDecimal creditLimit;
|
||||
@@ -187,6 +192,15 @@ public class Apps extends BaseEntity
|
||||
{
|
||||
return publicKey;
|
||||
}
|
||||
public void setPrivateKey(String privateKey)
|
||||
{
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
|
||||
public String getPrivateKey()
|
||||
{
|
||||
return privateKey;
|
||||
}
|
||||
public void setCreditLimit(BigDecimal creditLimit)
|
||||
{
|
||||
this.creditLimit = creditLimit;
|
||||
@@ -256,6 +270,7 @@ public class Apps extends BaseEntity
|
||||
.append("trxBalance", getTrxBalance())
|
||||
.append("usdtBalance", getUsdtBalance())
|
||||
.append("publicKey", getPublicKey())
|
||||
.append("privateKey", "<redacted>")
|
||||
.append("creditLimit", getCreditLimit())
|
||||
.append("googleSub", getGoogleSub())
|
||||
.append("googleEmail", getGoogleEmail())
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.ruoyi.system.domain;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||
import com.ruoyi.common.annotation.Excel;
|
||||
@@ -56,6 +57,9 @@ public class AppsPlus implements Serializable
|
||||
/** 公钥 */
|
||||
@Excel(name = "公钥")
|
||||
private String publicKey;
|
||||
/** 加密后的私钥,禁止序列化到接口响应 */
|
||||
@JsonIgnore
|
||||
private String privateKey;
|
||||
/** 信用额度 */
|
||||
@Excel(name = "信用额度金额")
|
||||
private BigDecimal creditLimit;
|
||||
@@ -173,6 +177,15 @@ public class AppsPlus implements Serializable
|
||||
{
|
||||
return publicKey;
|
||||
}
|
||||
public void setPrivateKey(String privateKey)
|
||||
{
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
|
||||
public String getPrivateKey()
|
||||
{
|
||||
return privateKey;
|
||||
}
|
||||
public void setCreditLimit(BigDecimal creditLimit)
|
||||
{
|
||||
this.creditLimit = creditLimit;
|
||||
@@ -242,6 +255,7 @@ public class AppsPlus implements Serializable
|
||||
.append("trxBalance", getTrxBalance())
|
||||
.append("usdtBalance", getUsdtBalance())
|
||||
.append("publicKey", getPublicKey())
|
||||
.append("privateKey", "<redacted>")
|
||||
.append("creditLimit", getCreditLimit())
|
||||
.append("googleSub", getGoogleSub())
|
||||
.append("googleEmail", getGoogleEmail())
|
||||
|
||||
@@ -2,7 +2,7 @@ package com.ruoyi.system.domain.vo;
|
||||
|
||||
/**
|
||||
* RSA 密钥对生成结果,公钥为 X.509 PEM,私钥为 PKCS#8 PEM。
|
||||
* privateKey 只在生成接口本次响应中出现,服务端绝不持久化。
|
||||
* 仅供服务层内部传递。privateKey 写入数据库前必须加密,禁止放入 HTTP 响应。
|
||||
*/
|
||||
public class AppKeyPairResult {
|
||||
private final String algorithm;
|
||||
|
||||
@@ -21,8 +21,8 @@ public interface AppsMapper extends BaseMapper<AppsPlus>
|
||||
/** 查询用户当前未删除的应用数量。 */
|
||||
int countActiveAppsByUserId(@Param("userId") Long userId);
|
||||
|
||||
int updatePublicKey(@Param("id") Long id, @Param("publicKey") String publicKey,
|
||||
@Param("updatedAt") java.util.Date updatedAt);
|
||||
int updateKeyPair(@Param("id") Long id, @Param("publicKey") String publicKey,
|
||||
@Param("privateKey") String privateKey, @Param("updatedAt") java.util.Date updatedAt);
|
||||
|
||||
int softDeleteAppsByIds(@Param("ids") Long[] ids, @Param("deletedAt") java.util.Date deletedAt);
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.ruoyi.system.service;
|
||||
|
||||
import com.ruoyi.common.exception.CustomException;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
/** 使用外部配置的主密钥加密商户 RSA 私钥。 */
|
||||
@Component
|
||||
public class AppPrivateKeyCipher {
|
||||
private static final String VERSION = "v1";
|
||||
private static final int IV_LENGTH = 12;
|
||||
private static final int GCM_TAG_BITS = 128;
|
||||
private static final int MIN_MASTER_KEY_LENGTH = 32;
|
||||
private final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
@Value("${payment.apps-private-key-encryption-key:}")
|
||||
private String masterKey;
|
||||
|
||||
public String encrypt(String plaintext) {
|
||||
if (plaintext == null || plaintext.trim().isEmpty()) {
|
||||
throw new CustomException("商户私钥不能为空");
|
||||
}
|
||||
try {
|
||||
byte[] iv = new byte[IV_LENGTH];
|
||||
secureRandom.nextBytes(iv);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey(), new GCMParameterSpec(GCM_TAG_BITS, iv));
|
||||
byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
|
||||
return VERSION + ":" + Base64.getEncoder().encodeToString(iv) + ":"
|
||||
+ Base64.getEncoder().encodeToString(ciphertext);
|
||||
} catch (CustomException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new CustomException("商户私钥加密失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
public String decrypt(String encryptedValue) {
|
||||
if (encryptedValue == null || encryptedValue.trim().isEmpty()) {
|
||||
throw new CustomException("商户私钥尚未配置");
|
||||
}
|
||||
try {
|
||||
String[] parts = encryptedValue.split(":", 3);
|
||||
if (parts.length != 3 || !VERSION.equals(parts[0])) {
|
||||
throw new CustomException("商户私钥密文格式不受支持");
|
||||
}
|
||||
byte[] iv = Base64.getDecoder().decode(parts[1]);
|
||||
byte[] ciphertext = Base64.getDecoder().decode(parts[2]);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, encryptionKey(), new GCMParameterSpec(GCM_TAG_BITS, iv));
|
||||
return new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8);
|
||||
} catch (CustomException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new CustomException("商户私钥解密失败,请检查加密主密钥", e);
|
||||
}
|
||||
}
|
||||
|
||||
private SecretKeySpec encryptionKey() throws Exception {
|
||||
if (masterKey == null || masterKey.length() < MIN_MASTER_KEY_LENGTH) {
|
||||
throw new CustomException("未配置 payment.apps-private-key-encryption-key 或长度不足 32 位");
|
||||
}
|
||||
byte[] key = MessageDigest.getInstance("SHA-256").digest(masterKey.getBytes(StandardCharsets.UTF_8));
|
||||
return new SecretKeySpec(key, "AES");
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import com.ruoyi.system.domain.AppsPlus;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import com.ruoyi.common.select.SelectItem;
|
||||
import com.ruoyi.system.domain.vo.AppKeyPairResult;
|
||||
/**
|
||||
* 应用管理Service接口
|
||||
*
|
||||
@@ -16,11 +15,11 @@ import com.ruoyi.system.domain.vo.AppKeyPairResult;
|
||||
public interface IAppsService extends IService<AppsPlus>
|
||||
{
|
||||
|
||||
/** 生成 RSA 密钥对。私钥仅由返回值交付,不持久化。 */
|
||||
AppKeyPairResult generateKeyPair();
|
||||
/** 为指定应用生成并持久化新的 RSA 密钥对。 */
|
||||
int rotateKeyPair(Long id, boolean isUser);
|
||||
|
||||
/** 单独设置并规范化商户 RSA 公钥。 */
|
||||
int updatePublicKey(Long id, String publicKey, boolean isUser);
|
||||
/** 解密应用私钥,仅供后端受控业务调用,禁止直接暴露到 HTTP 响应。 */
|
||||
String decryptPrivateKey(Long id, boolean isUser);
|
||||
|
||||
/** 获取新应用固定使用的全局归集地址。 */
|
||||
String getGlobalAggregationAddress();
|
||||
|
||||
@@ -15,6 +15,7 @@ import com.ruoyi.system.mapper.AppsMapper;
|
||||
import com.ruoyi.system.mapper.UsdtConfigMapper;
|
||||
import com.ruoyi.system.domain.UsdtConfig;
|
||||
import com.ruoyi.system.service.IAppsService;
|
||||
import com.ruoyi.system.service.AppPrivateKeyCipher;
|
||||
import com.ruoyi.system.domain.vo.AppKeyPairResult;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
@@ -22,11 +23,8 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Base64;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -48,13 +46,14 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
|
||||
private UsdtConfigMapper usdtConfigMapper;
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
@Autowired
|
||||
private AppPrivateKeyCipher privateKeyCipher;
|
||||
|
||||
/**
|
||||
* 生成与平台加解密约定一致的 RSA 密钥对。
|
||||
* 私钥不进入实体、数据库或日志,只随本次方法结果返回给调用方。
|
||||
* 私钥仅在内存中短暂存在,写入数据库前必须加密。
|
||||
*/
|
||||
@Override
|
||||
public AppKeyPairResult generateKeyPair() {
|
||||
private AppKeyPairResult generateKeyPair() {
|
||||
try {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(RSA_KEY_SIZE);
|
||||
@@ -68,10 +67,17 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updatePublicKey(Long id, String publicKey, boolean isUser) {
|
||||
public int rotateKeyPair(Long id, boolean isUser) {
|
||||
Apps current = requireExistingApp(id, isUser);
|
||||
String normalizedPublicKey = normalizeAndValidatePublicKey(publicKey);
|
||||
return appsMapper.updatePublicKey(current.getId(), normalizedPublicKey, DateUtils.getNowDate());
|
||||
AppKeyPairResult keyPair = generateKeyPair();
|
||||
return appsMapper.updateKeyPair(current.getId(), keyPair.getPublicKey(),
|
||||
privateKeyCipher.encrypt(keyPair.getPrivateKey()), DateUtils.getNowDate());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String decryptPrivateKey(Long id, boolean isUser) {
|
||||
Apps current = requireExistingApp(id, isUser);
|
||||
return privateKeyCipher.decrypt(current.getPrivateKey());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -315,9 +321,10 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
|
||||
if (apps.getTrxBalance() == null) apps.setTrxBalance(BigDecimal.ZERO);
|
||||
if (apps.getUsdtBalance() == null) apps.setUsdtBalance(BigDecimal.ZERO);
|
||||
if (apps.getCreditLimit() == null) apps.setCreditLimit(BigDecimal.ZERO);
|
||||
if (StringUtils.isNotBlank(apps.getPublicKey())) {
|
||||
apps.setPublicKey(normalizeAndValidatePublicKey(apps.getPublicKey()));
|
||||
}
|
||||
// 公私钥只允许系统生成,忽略请求中传入的任何密钥字段。
|
||||
AppKeyPairResult keyPair = generateKeyPair();
|
||||
apps.setPublicKey(keyPair.getPublicKey());
|
||||
apps.setPrivateKey(privateKeyCipher.encrypt(keyPair.getPrivateKey()));
|
||||
return appsMapper.insertApps(apps);
|
||||
}
|
||||
|
||||
@@ -418,27 +425,6 @@ public class AppsServiceImpl extends ServiceImpl<AppsMapper, AppsPlus> implement
|
||||
if (value != null && value.signum() < 0) throw new CustomException(fieldName + "不能小于 0");
|
||||
}
|
||||
|
||||
private String normalizeAndValidatePublicKey(String publicKey) {
|
||||
if (StringUtils.isBlank(publicKey)) throw new CustomException("公钥不能为空");
|
||||
String normalized = publicKey.trim()
|
||||
.replace("-----BEGIN PUBLIC KEY-----", "")
|
||||
.replace("-----END PUBLIC KEY-----", "")
|
||||
.replaceAll("\\s", "");
|
||||
try {
|
||||
byte[] encoded = Base64.getDecoder().decode(normalized);
|
||||
RSAPublicKey key = (RSAPublicKey) KeyFactory.getInstance("RSA")
|
||||
.generatePublic(new X509EncodedKeySpec(encoded));
|
||||
if (key.getModulus().bitLength() < RSA_KEY_SIZE) {
|
||||
throw new CustomException("RSA 公钥长度不能小于 2048 位");
|
||||
}
|
||||
return Base64.getEncoder().encodeToString(key.getEncoded());
|
||||
} catch (CustomException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new CustomException("公钥格式错误,请使用 X.509 Base64 或 PUBLIC KEY PEM 格式");
|
||||
}
|
||||
}
|
||||
|
||||
/** 将 DER 密钥编码为标准 PEM,正文固定每行 64 个字符。 */
|
||||
private String toPem(String type, byte[] encodedKey) {
|
||||
String body = Base64.getMimeEncoder(64, new byte[] { '\n' }).encodeToString(encodedKey);
|
||||
|
||||
Reference in new issue
Block a user