Spring Boot中使用Bouncy Castle實現SM2國密算法(與前端JS加密交互)
- 一、環境準備
- 二、核心實現
- 三、前后端交互流程
- 四、關鍵問題解決方案
- 五、常見問題排查
- 六、最佳實踐建議

在現代Web應用中,數據安全傳輸至關重要。SM2作為我國自主設計的非對稱加密算法,在安全性、效率和合規性方面具有顯著優勢。本文將詳細介紹如何在Spring Boot中集成SM2算法,實現與前端JS的無縫加密交互。
一、環境準備
技術棧:
- Java 1.8
- Spring Boot 2.1.18
- Bouncy Castle 1.68+
- 前端:sm-crypto或類似庫
Maven核心依賴:
<dependencies><dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.68</version></dependency>
</dependencies>
二、核心實現
- 密鑰生成服務
@RestController
@RequestMapping("/sm2")
public class SM2Controller {@GetMapping("/keypair")public Map<String, String> generateKeyPair() throws Exception {KeyPair keyPair = SM2CryptoUtil.generateKeyPair();ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();String publicKeyHex = Hex.toHexString(publicKey.getQ().getEncoded(false));String privateKeyHex = privateKey.getD().toString(16);// 標準化私鑰格式(64字符)privateKeyHex = String.format("%64s", privateKeyHex).replace(' ', '0');return Map.of("publicKey", publicKeyHex, // 130字符帶04前綴"privateKey", privateKeyHex // 64字符);}
}
- SM2解密服務
import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.BigIntegers;
import org.bouncycastle.util.encoders.Hex;import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;/*** @author cmamg* @title: Base64Util* @projectName * @description: TODO* @date 2025/7/29*/
public class SM2CryptoUtil {// 加密模式常量public static final int C1C2C3 = 0;public static final int C1C3C2 = 1;// 橢圓曲線參數private static final X9ECParameters EC_PARAMS;private static final ECDomainParameters DOMAIN_PARAMS;private static final BigInteger CURVE_ORDER;static {Security.addProvider(new BouncyCastleProvider());EC_PARAMS = GMNamedCurves.getByName("sm2p256v1");DOMAIN_PARAMS = new ECDomainParameters(EC_PARAMS.getCurve(),EC_PARAMS.getG(),EC_PARAMS.getN(),EC_PARAMS.getH());CURVE_ORDER = EC_PARAMS.getN();}/*** 生成SM2密鑰對*/public static KeyPair generateKeyPair() throws Exception {ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("sm2p256v1");KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", "BC");kpg.initialize(spec, new SecureRandom());return kpg.generateKeyPair();}/*** 獲取壓縮公鑰十六進制字符串*/public static String getCompressedPublicKey(ECPoint publicKey) {byte[] compressed = publicKey.getEncoded(true);return Hex.toHexString(compressed);}/*** 獲取未壓縮公鑰十六進制字符串(不帶04前綴)*/public static String getUncompressedPublicKey(ECPoint publicKey) {byte[] uncompressed = publicKey.getEncoded(false);// 去掉開頭的04標識return Hex.toHexString(uncompressed);}/*** 從十六進制字符串解析公鑰*/public static ECPoint parsePublicKey(String publicKeyHex) {// 添加04前綴表示未壓縮格式byte[] pubKeyBytes = Hex.decode( publicKeyHex);return DOMAIN_PARAMS.getCurve().decodePoint(pubKeyBytes);}private static BigInteger parsePrivateKey(String privateKeyHex) {if (privateKeyHex == null || privateKeyHex.length() != 64) {throw new IllegalArgumentException("私鑰必須是64字符十六進制字符串");}try {BigInteger privateKey = new BigInteger(privateKeyHex, 16);// 驗證私鑰范圍 [1, n-1]if (privateKey.signum() <= 0 || privateKey.compareTo(CURVE_ORDER) >= 0) {throw new IllegalArgumentException("私鑰超出有效范圍");}return privateKey;} catch (NumberFormatException e) {throw new IllegalArgumentException("無效的私鑰格式", e);}}public static String decryptStr(String ciphertextHex, String privateKeyHex) throws Exception {return new String(decrypt(ciphertextHex,privateKeyHex, 1), "UTF-8");}/*** SM2解密*/public static byte[] decrypt(String ciphertextHex, String privateKeyHex, int cipherMode) throws Exception {// 1. 驗證并解析私鑰BigInteger privateKey = parsePrivateKey(privateKeyHex);// 2. 解析密文byte[] ciphertext = Hex.decode(ciphertextHex);// 驗證最小長度 = C1(64) + C3(32) = 96字節if (ciphertext.length < 96) {throw new IllegalArgumentException("密文太短");}// 3. 拆分密文byte[] c1 = Arrays.copyOfRange(ciphertext, 0, 64); // 64字節byte[] c3;byte[] c2;if (cipherMode == C1C2C3) {// C1C2C3模式: C1(64) + C2 + C3(32)c3 = Arrays.copyOfRange(ciphertext, ciphertext.length - 32, ciphertext.length);c2 = Arrays.copyOfRange(ciphertext, 64, ciphertext.length - 32);} else {// C1C3C2模式: C1(64) + C3(32) + C2c3 = Arrays.copyOfRange(ciphertext, 64, 96);c2 = Arrays.copyOfRange(ciphertext, 96, ciphertext.length);}// 4. 重建C1點byte[] c1Full = new byte[65]; // 04 + 64字節c1Full[0] = 0x04; // 添加未壓縮標識System.arraycopy(c1, 0, c1Full, 1, 64);ECPoint c1Point;try {c1Point = DOMAIN_PARAMS.getCurve().decodePoint(c1Full);} catch (Exception e) {throw new IllegalArgumentException("無效的C1點", e);}// 5. 計算共享點 (x2, y2) = privateKey * C1ECPoint s = c1Point.multiply(privateKey).normalize();// 驗證點是否在曲線上if (!s.isValid()) {throw new SecurityException("計算出的點不在曲線上");}byte[] x2 = BigIntegers.asUnsignedByteArray(32, s.getXCoord().toBigInteger());byte[] y2 = BigIntegers.asUnsignedByteArray(32, s.getYCoord().toBigInteger());// 6. KDF生成密鑰流byte[] z = new byte[x2.length + y2.length];System.arraycopy(x2, 0, z, 0, x2.length);System.arraycopy(y2, 0, z, x2.length, y2.length);byte[] t = kdf(z, c2.length);// 7. 異或解密byte[] msg = new byte[c2.length];for (int i = 0; i < c2.length; i++) {msg[i] = (byte) (c2[i] ^ t[i]);}// 8. 驗證C3byte[] u = new byte[x2.length + msg.length + y2.length];System.arraycopy(x2, 0, u, 0, x2.length);System.arraycopy(msg, 0, u, x2.length, msg.length);System.arraycopy(y2, 0, u, x2.length + msg.length, y2.length);byte[] calculatedC3 = sm3(u);if (!Arrays.equals(c3, calculatedC3)) {throw new SecurityException("C3驗證失敗: 數據可能被篡改或密鑰錯誤");}return msg;}/*** KDF密鑰派生函數*/private static byte[] kdf(byte[] z, int keylen) {int ct = 1;int offset = 0;byte[] result = new byte[keylen];SM3Digest digest = new SM3Digest();while (offset < keylen) {// 準備計數器字節byte[] ctBytes = new byte[]{(byte) (ct >>> 24),(byte) (ct >>> 16),(byte) (ct >>> 8),(byte) ct};// 計算SM3哈希digest.update(z, 0, z.length);digest.update(ctBytes, 0, 4);byte[] hash = new byte[digest.getDigestSize()];digest.doFinal(hash, 0);// 填充結果int copyLen = Math.min(keylen - offset, hash.length);System.arraycopy(hash, 0, result, offset, copyLen);offset += copyLen;ct++;digest.reset();}return result;}/*** SM3哈希計算*/private static byte[] sm3(byte[] input) {SM3Digest digest = new SM3Digest();digest.update(input, 0, input.length);byte[] hash = new byte[digest.getDigestSize()];digest.doFinal(hash, 0);return hash;}
}
- 前端加密示例
import { sm2 } from 'sm-crypto';// 使用后端生成的公鑰(130字符帶04前綴)
const publicKey = '04d4de...'; function encryptMessage(message) {// 使用C1C3C2模式加密const ciphertext = sm2.doEncrypt(message, publicKey, 1 // cipherMode=1 表示C1C3C2);return ciphertext; // 十六進制字符串
}// 調用示例
const encrypted = encryptMessage('敏感數據123');
三、前后端交互流程
密鑰獲取:
GET /sm2/keypair
Response: { "publicKey": "04...", "privateKey": "a1b2..." }
前端加密:
const ciphertext = sm2.doEncrypt(data, publicKey, 1);
后端解密:
POST /sm2/decrypt
{"ciphertext": "a1b2c3...","privateKey": "a1b2...","mode": 1
}
四、關鍵問題解決方案
- 公鑰格式一致性
前端要求公鑰帶04前綴(未壓縮格式),后端需確保:
public String getPublicKeyHex(ECPoint publicKey) {return Hex.toHexString(publicKey.getEncoded(false)); // 帶04前綴
}
- 私鑰范圍驗證
防止Scalar not in interval錯誤:
private static final BigInteger CURVE_ORDER = EC_PARAMS.getN();if (privateKey.signum() <= 0 || privateKey.compareTo(CURVE_ORDER) >= 0) {throw new IllegalArgumentException("無效私鑰范圍");
}
- C1點重建
前端密文中的C1點不帶04前綴,后端需重建:
byte[] c1Full = new byte[65];
c1Full[0] = 0x04; // 添加前綴
System.arraycopy(c1, 0, c1Full, 1, 64);
五、常見問題排查
錯誤現象 可能原因 解決方案
Scalar not in interval 私鑰格式錯誤或越界 驗證私鑰長度64字符,值在[1, n-1]范圍內
C3驗證失敗 密鑰錯誤或數據篡改 檢查公私鑰配對,重試加密流程
無效的C1點 密文格式錯誤 確認使用C1C3C2模式,檢查密文長度
解密亂碼 編碼不一致 統一使用UTF-8編碼
六、最佳實踐建議
密鑰管理:
前端不存儲私鑰
后端使用HSM或KMS管理私鑰
定期輪換密鑰
性能優化:
// 重用SM3Digest實例
private static final ThreadLocal<SM3Digest> sm3Cache = ThreadLocal.withInitial(SM3Digest::new);
安全增強:
// 防止時序攻擊
if (!MessageDigest.isEqual(c3, calculatedC3)) {throw new SecurityException("C3驗證失敗");
}
七、總結
本文實現了Spring Boot中完整的SM2算法集成方案,重點解決了:
密鑰生成與格式標準化
與前端JS的加密交互
解密過程中的異常處理
通過此方案,開發者可以快速構建符合國密標準的安全應用,確保數據傳輸的機密性和完整性。在實際業務中,建議結合HTTPS等傳輸層安全措施,構建縱深防御體系。