package com.yau.digitalrmb.walletopening.application; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeyPairResult; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeyService; import com.yau.digitalrmb.institutionidentity.application.InstitutionKeySubject; import com.yau.digitalrmb.institutionidentity.infrastructure.SmInstitutionIdentityCryptography; import com.yau.digitalrmb.shared.api.ErrorCode; import com.yau.digitalrmb.shared.exception.BusinessException; import com.yau.digitalrmb.walletopening.domain.CentralWalletRegistration; import com.yau.digitalrmb.walletopening.domain.CentralWalletRegistrationRepository; import com.yau.digitalrmb.walletopening.domain.WalletRegistrationRequest; import com.yau.digitalrmb.walletopening.domain.WalletRegistrationRequestRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @Service public class CentralWalletRegistrationService { private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd"); @Resource private CentralWalletRegistrationRepository centralRepository; @Resource private WalletRegistrationRequestRepository registrationRepository; @Resource private InstitutionKeyService institutionKeyService; @Resource private SmInstitutionIdentityCryptography cryptography; @Resource private WalletOpeningScoreService scoreService; @Transactional(readOnly = true) public CentralWalletRegistrationPageResult getPage(InstitutionKeySubject subject) { CentralWalletRegistration c = centralRepository .findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId()).orElse(null); if (c == null || !c.isReceived()) { WalletRegistrationRequest req = registrationRepository .findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId()).orElse(null); if (req != null && req.isSentToCentral() && (c == null || !c.isReceived())) { return new CentralWalletRegistrationPageResult(c); } } return new CentralWalletRegistrationPageResult(c); } @Transactional(readOnly = true) public InstitutionKeyPairResult getCentralKey(InstitutionKeySubject subject) { return institutionKeyService.centralBankKey(subject, "central-bank"); } @Transactional public ReceiveResult receive(InstitutionKeySubject subject) { CentralWalletRegistration c = getOrCreate(subject); if (c.isReceived()) { return new ReceiveResult(c.getRequestJson(), c.getRequestMessage(), c.getDigestValue(), c.getSignature()); } WalletRegistrationRequest req = registrationRepository .findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId()) .orElse(null); if (req == null || !req.isSentToCentral()) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "尚未收到商业银行发送的备案请求"); } String receiveTime = LocalDateTime.now().format(TIMESTAMP_FORMAT); c.receive(req, receiveTime); centralRepository.update(c); return new ReceiveResult(c.getRequestJson(), c.getRequestMessage(), c.getDigestValue(), c.getSignature()); } @Transactional public String verifySignature(InstitutionKeySubject subject, String publicKeyInput, String algorithm) { if (!"SM2".equalsIgnoreCase(algorithm != null ? algorithm.trim() : "")) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "算法选择有误,错误数+1"); } CentralWalletRegistration c = getOrCreate(subject); if (!c.isReceived()) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先接收备案请求信息"); } String storedPublicKey = institutionKeyService.commercialBankSecondPublicKeyOrNull(subject); if (storedPublicKey == null) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "商业银行第二公钥不存在,请先在模块一生成机构密钥"); } boolean keyMatches = storedPublicKey.equalsIgnoreCase(publicKeyInput.trim()); if (!keyMatches) { c.verifySignature(publicKeyInput, false); centralRepository.update(c); scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "选择的公钥与商业银行第二公钥不匹配"); } boolean verified = cryptography.verify(storedPublicKey, c.getDigestValue(), c.getSignature()); c.verifySignature(publicKeyInput.trim(), verified); if (!verified) { centralRepository.update(c); scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "签名验证失败"); } centralRepository.update(c); return c.getSignVerifyResult(); } @Transactional public String recalculateDigest(InstitutionKeySubject subject, String requestMessageInput, String algorithm) { if (!"SM3".equalsIgnoreCase(algorithm != null ? algorithm.trim() : "")) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "算法选择有误,错误数+1"); } CentralWalletRegistration c = getOrCreate(subject); if (c.getSignVerifyResult() == null || !c.getSignVerifyResult().startsWith("通过")) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先完成签名验证"); } String newDigest = cryptography.sm3(requestMessageInput); c.recalculateDigest(newDigest); centralRepository.update(c); return c.getRecalculatedDigest(); } @Transactional public String matchDigest(InstitutionKeySubject subject) { CentralWalletRegistration c = getOrCreate(subject); if (c.getRecalculatedDigest() == null) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先计算新摘要值H2"); } boolean matches = c.getRecalculatedDigest().equalsIgnoreCase(c.getDigestValue()); c.matchDigest(matches); if (!matches) { centralRepository.update(c); scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "摘要不匹配,报文可能被篡改"); } centralRepository.update(c); return c.getDigestMatchResult(); } @Transactional public String cbSign(InstitutionKeySubject subject, String privateKeyInput, String algorithm) { if (!"SM2".equalsIgnoreCase(algorithm != null ? algorithm.trim() : "")) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "算法选择有误,错误数+1"); } CentralWalletRegistration c = getOrCreate(subject); if (c.getDigestMatchResult() == null || !c.getDigestMatchResult().startsWith("通过")) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先完成摘要完整性校验"); } if (c.getCbRootSignature() != null) { return c.getCbRootSignature(); } String storedPrivateKey = institutionKeyService.centralBankFirstPrivateKeyOrNull(subject); if (storedPrivateKey == null) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "央行第一私钥不存在,请先生成央行密钥对"); } if (!storedPrivateKey.equalsIgnoreCase(privateKeyInput.trim())) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "签名密钥错误,请使用正确的央行第一私钥"); } String sig = cryptography.sign(storedPrivateKey, c.getDigestValue()); String cbSignature = "CB_ROOT_SIG_" + sig; c.cbSign(privateKeyInput.trim(), cbSignature); centralRepository.update(c); return c.getCbRootSignature(); } @Transactional public boolean updateWalletRegister(InstitutionKeySubject subject) { CentralWalletRegistration c = getOrCreate(subject); if (c.getCbRootSignature() == null) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先完成央行根签"); } c.registerWallet(); centralRepository.update(c); return c.isWalletRegistered(); } @Transactional public CentralWalletConfirmResult outputConfirm(InstitutionKeySubject subject) { CentralWalletRegistration c = getOrCreate(subject); if (c.getConfirmJson() != null) { return buildConfirmResult(c); } if (!c.isWalletRegistered()) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先更新钱包登记备案"); } String date = LocalDateTime.now().format(DATE_FORMAT); String confirmId = "REG_CONFIRM_" + date + "_001"; String registerTime = LocalDateTime.now().format(TIMESTAMP_FORMAT); String json = buildConfirmJson(confirmId, c.getWalletId(), c.getCbRootSignature(), registerTime); c.confirm(confirmId, json); centralRepository.update(c); return buildConfirmResult(c); } @Transactional public boolean send(InstitutionKeySubject subject) { CentralWalletRegistration c = getOrCreate(subject); if (c.getConfirmJson() == null) { scoreService.recordError(subject.getUserId()); throw new BusinessException(ErrorCode.VALIDATION_ERROR, "请先输出备案确认报文"); } c.send(); centralRepository.update(c); return c.isSent(); } private CentralWalletConfirmResult buildConfirmResult(CentralWalletRegistration c) { return new CentralWalletConfirmResult( c.getConfirmId(), c.getWalletId(), "REGISTERED", c.getCbRootSignature(), c.getReceiveTime()); } private String buildConfirmJson(String confirmId, String walletId, String cbSig, String registerTime) { return "{\n" + " \"confirmId\": \"" + confirmId + "\",\n" + " \"walletId\": \"" + walletId + "\",\n" + " \"registrationStatus\": \"REGISTERED\",\n" + " \"cbRootSignature\": \"" + cbSig + "\",\n" + " \"registerTime\": \"" + registerTime + "\"\n" + "}"; } private CentralWalletRegistration getOrCreate(InstitutionKeySubject subject) { return centralRepository .findLatest(subject.getUserId(), subject.getSchoolId(), subject.getClassId()) .orElseGet(() -> centralRepository.save( CentralWalletRegistration.create(subject.getUserId(), subject.getSchoolId(), subject.getClassId()))); } }