
Vue前端与.Net后端SM2加密通信实战从sm-crypto到BouncyCastle的完整流程在前后端分离架构中数据安全传输一直是开发者关注的重点。国密算法SM2作为我国自主研发的非对称加密标准正逐渐成为金融、政务等领域的安全通信首选方案。本文将带你深入实践Vue前端与.Net后端基于SM2算法的加密通信解决开发过程中密钥格式、加密模式等实际对接难题。1. 环境准备与基础概念1.1 前端环境配置Vue项目中使用sm-crypto库实现SM2加密npm install sm-crypto --save安装后可通过以下方式引入import { sm2 } from sm-crypto关键配置项说明cipherMode加密模式0为C1C2C31为C1C3C2publicKey后端提供的十六进制格式公钥1.2 后端环境搭建.Net项目需通过NuGet添加BouncyCastle依赖Install-Package Portable.BouncyCastle -Version 1.9.0创建SM2工具类时需注意曲线参数必须符合国密标准密钥对生成需使用SM2.Instance单例提示建议后端统一维护密钥对避免每次请求重新生成2. 密钥生成与格式处理2.1 后端密钥生成实现public static SM2Model GetKeyPair() { SM2 sm2 SM2.Instance; AsymmetricCipherKeyPair key sm2.ecc_key_pair_generator.GenerateKeyPair(); ECPrivateKeyParameters ecpriv (ECPrivateKeyParameters)key.Private; ECPublicKeyParameters ecpub (ECPublicKeyParameters)key.Public; return new SM2Model { PrivateKey Hex.Encode(ecpriv.D.ToByteArray()), PublicKey Hex.Encode(ecpub.Q.GetEncoded()) }; }密钥格式要点公钥04开头未压缩格式包含X,Y坐标私钥32字节大整数编码方式十六进制字符串UpperCase2.2 前端密钥格式适配Vue端需要处理Base64与Hex的转换// 公钥预处理 function formatPublicKey(key) { return key.startsWith(04) ? key : 04${key} } // 示例使用 const pubKey formatPublicKey(xxx...)3. 加密通信实现细节3.1 前端加密实现Vue组件中的加密示例export default { methods: { encryptData(content) { const cipherMode 0 // C1C2C3模式 const pubKey this.$store.state.crypto.publicKey try { return sm2.doEncrypt(content, pubKey, cipherMode) } catch (e) { console.error(加密失败:, e) return null } } } }常见问题排查公钥格式错误确保包含04前缀加密模式不匹配前后端需统一使用相同模式内容编码统一使用UTF-8编码3.2 后端解密处理C#解密工具类关键代码public static string Decrypt(string privateKeyHex, string encryptedData) { byte[] privateKey Hex.Decode(privateKeyHex); byte[] encryptedBytes Hex.Decode(encryptedData); // 拆分密文组件 byte[] c1Bytes encryptedBytes.Take(65).ToArray(); byte[] c2 encryptedBytes.Skip(65).Take(encryptedBytes.Length - 97).ToArray(); byte[] c3 encryptedBytes.Skip(65 c2.Length).Take(32).ToArray(); // 执行解密 SM2 sm2 SM2.Instance; BigInteger userD new BigInteger(1, privateKey); ECPoint c1 sm2.ecc_curve.DecodePoint(c1Bytes); Cipher cipher new Cipher(); cipher.Init_dec(userD, c1); cipher.Decrypt(c2); cipher.Dofinal(c3); return Encoding.UTF8.GetString(c2); }4. 联调技巧与性能优化4.1 调试技巧前端调试工具// 在加密前打印关键参数 console.log(PublicKey:, publicKey) console.log(Content:, content) console.log(CipherMode:, cipherMode)后端日志记录_logger.LogDebug($Received encrypted data: {encryptedData.Substring(0, 30)}...); _logger.LogDebug($Using private key: {privateKey.Substring(0, 16)}...);4.2 性能优化方案前端缓存策略会话期间缓存公钥批量数据分块加密后端优化建议使用静态SM2实例预计算常用参数// 优化后的工具类结构 public static class SM2Helper { private static readonly SM2 _sm2 SM2.Instance; private static readonly Cipher _cipher new Cipher(); public static string OptimizedDecrypt(string privateKey, string data) { // 优化后的实现... } }4.3 安全增强措施密钥轮换机制定期自动更新密钥对新旧密钥并行期传输层保护结合HTTPS使用添加时间戳防重放// 前端安全增强示例 function secureEncrypt(content) { const timestamp Date.now() const nonce generateNonce() const data ${timestamp}|${nonce}|${content} return sm2.doEncrypt(data, publicKey, 0) }在实际项目部署中我们发现最常出现的问题是前后端加密模式不一致导致的解密失败。通过统一约定cipherMode参数推荐使用0-C1C2C3模式并在接口文档中明确标注可以避免80%以上的联调问题。