package com.ruoyi.common.utils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.security.KeyPair; import java.security.PrivateKey; import java.security.PublicKey; /** * 增强版SM2工具类 */ @Component public class SM2EnhancedUtil { @Value("${sm2.private-key}") private String configPrivateKey; @Value("${sm2.public-key}") private String configPublicKey; private PrivateKey privateKey; private PublicKey publicKey; private KeyPair keyPair; @PostConstruct public void init() { // 如果配置了密钥,则使用配置的密钥 if (configPrivateKey != null && !configPrivateKey.trim().isEmpty() && configPublicKey != null && !configPublicKey.trim().isEmpty()) { this.privateKey = SM2Util.loadPrivateKey(configPrivateKey); this.publicKey = SM2Util.loadPublicKey(configPublicKey); this.keyPair = new KeyPair(publicKey, privateKey); } else { // 否则生成新的密钥对 this.keyPair = SM2Util.generateKeyPair(); this.privateKey = keyPair.getPrivate(); this.publicKey = keyPair.getPublic(); // 输出生成的密钥(仅用于开发环境) System.out.println("生成的SM2公钥: " + getPublicKeyBase64()); System.out.println("生成的SM2私钥: " + getPrivateKeyBase64()); } } /** * 使用配置的私钥签名 */ public String sign(String data) { return SM2Util.sign(data.getBytes(), privateKey); } /** * 使用配置的公钥验签 */ public boolean verify(String data, String signature) { return SM2Util.verify(data.getBytes(), signature, publicKey); } /** * 使用配置的私钥签名(字节数组) */ public String sign(byte[] data) { return SM2Util.sign(data, privateKey); } /** * 使用配置的公钥验签(字节数组) */ public boolean verify(byte[] data, String signature) { return SM2Util.verify(data, signature, publicKey); } /** * 获取当前使用的私钥(Base64) */ public String getPrivateKeyBase64() { return SM2Util.privateKeyToString(privateKey); } /** * 获取当前使用的公钥(Base64) */ public String getPublicKeyBase64() { return SM2Util.publicKeyToString(publicKey); } /** * 获取密钥对 */ public KeyPair getKeyPair() { return keyPair; } /** * 生成新的密钥对并更新当前实例 */ public void generateNewKeyPair() { this.keyPair = SM2Util.generateKeyPair(); this.privateKey = keyPair.getPrivate(); this.publicKey = keyPair.getPublic(); } /** * 验证工具类是否正常工作 */ public boolean selfCheck() { try { String testData = "SM2签名测试数据"; String signature = sign(testData); return verify(testData, signature); } catch (Exception e) { return false; } } }