From 35c7bcc8aa79aee7bce4a1a45081a0a5ef5baf34 Mon Sep 17 00:00:00 2001 From: luqingjie <544309509@qq.com> Date: Sat, 10 Oct 2026 03:33:51 -0400 Subject: [PATCH] =?UTF-8?q?apps=E6=B7=BB=E5=8A=A0=E7=A7=81=E9=92=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/resources/application.yml | 4 + .../system/controller/AppsController.java | 47 +++--------- .../java/com/ruoyi/system/domain/Apps.java | 15 ++++ .../com/ruoyi/system/domain/AppsPlus.java | 14 ++++ .../system/domain/vo/AppKeyPairResult.java | 2 +- .../com/ruoyi/system/mapper/AppsMapper.java | 4 +- .../system/service/AppPrivateKeyCipher.java | 74 +++++++++++++++++++ .../ruoyi/system/service/IAppsService.java | 9 +-- .../system/service/impl/AppsServiceImpl.java | 52 +++++-------- .../resources/mapper/system/AppsMapper.xml | 10 ++- 10 files changed, 152 insertions(+), 79 deletions(-) create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/service/AppPrivateKeyCipher.java diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index 3850091..6328621 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -129,6 +129,10 @@ token: secret: abcdefghijklmnopqrstuvwxyz # 令牌有效期(默认30分钟) expireTime: 525600 + +# 商户 RSA 私钥加密主密钥。生产环境必须通过环境变量注入,长度至少 32 位。 +payment: + apps-private-key-encryption-key: ${APP_PRIVATE_KEY_ENCRYPTION_KEY:} # MyBatis配置 mybatis: diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppsController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppsController.java index e089cdc..dabf7d0 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppsController.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppsController.java @@ -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')") diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/Apps.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/Apps.java index fb35811..3f241f6 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/Apps.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/Apps.java @@ -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", "") .append("creditLimit", getCreditLimit()) .append("googleSub", getGoogleSub()) .append("googleEmail", getGoogleEmail()) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppsPlus.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppsPlus.java index 38f3bc6..d832cff 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppsPlus.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppsPlus.java @@ -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", "") .append("creditLimit", getCreditLimit()) .append("googleSub", getGoogleSub()) .append("googleEmail", getGoogleEmail()) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/AppKeyPairResult.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/AppKeyPairResult.java index dfcc9bc..ee9a70a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/AppKeyPairResult.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/AppKeyPairResult.java @@ -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; 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 c73d0d5..e324e22 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,8 +21,8 @@ public interface AppsMapper extends BaseMapper /** 查询用户当前未删除的应用数量。 */ 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); /** 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 new file mode 100644 index 0000000..586e48e --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/AppPrivateKeyCipher.java @@ -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"); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/IAppsService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/IAppsService.java index b1e3eb3..3564a0c 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/IAppsService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/IAppsService.java @@ -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 { - /** 生成 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(); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AppsServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AppsServiceImpl.java index 30dbd96..c63bfb2 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AppsServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AppsServiceImpl.java @@ -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 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 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 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 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); diff --git a/ruoyi-system/src/main/resources/mapper/system/AppsMapper.xml b/ruoyi-system/src/main/resources/mapper/system/AppsMapper.xml index f8a71d5..cd0e1c7 100644 --- a/ruoyi-system/src/main/resources/mapper/system/AppsMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/system/AppsMapper.xml @@ -16,6 +16,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" + @@ -25,7 +26,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - select id, user_id, name, description, status, created_at, updated_at, deleted_at, trx_balance, usdt_balance, public_key, credit_limit, google_sub, google_email, google_name, google_picture, dist_token_address from apps + select id, user_id, name, description, status, created_at, updated_at, deleted_at, trx_balance, usdt_balance, public_key, private_key, credit_limit, google_sub, google_email, google_name, google_picture, dist_token_address from apps - + update apps - set public_key = #{publicKey}, updated_at = #{updatedAt} + set public_key = #{publicKey}, private_key = #{privateKey}, updated_at = #{updatedAt} where id = #{id} and deleted_at is null @@ -93,6 +94,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" trx_balance, usdt_balance, public_key, + private_key, credit_limit, google_sub, google_email, @@ -111,6 +113,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" #{trxBalance}, #{usdtBalance}, #{publicKey}, + #{privateKey}, #{creditLimit}, #{googleSub}, #{googleEmail}, @@ -133,6 +136,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" trx_balance = #{trxBalance}, usdt_balance = #{usdtBalance}, public_key = #{publicKey}, + private_key = #{privateKey}, credit_limit = #{creditLimit}, google_sub = #{googleSub}, google_email = #{googleEmail},