Vue 3/2 前端 JS 实现 SM2 国密加密完整指南

作者:性能诊所

时间:2026-11-01

浏览:350

本文详细介绍如何在 Vue 3 和 Vue 2 项目中集成并使用 sm-crypto 库实现 SM2 国密算法加密。涵盖从 npm 安装依赖、封装通用加密工具函数,到在组件中调用 encrypt 方法进行数据加密的完整步骤,提供可直接复用的代码示例。

文章目录

基于 Vue 3 框架

第一步:安装 SM2 加密库

首先,你需要安装合适的 SM2 加密库。在前面的讨论中提到了 js-sm2 这个 JavaScript 实现的 SM2 加密算法库,你可以使用 npm 或者 yarn 进行安装

npm install sm-crypto # 或者 yarn add sm-crypto或者pnpm install sm-crypto

第二步:引入 SM2 库并使用

在 Vue 3 的项目中,一般来说你会在需要加密的组件或者文件中引入 SM2 库,并使用其提供的加密、解密等功能。以下是一个简单的示例:

// 在需要加密的组件或者文件中引入
import smcrypto from 'sm-crypto'

const signIn = async () => {
  const userlogin = {
    username: formData.username,
    password: '04' + smcrypto.sm2.doEncrypt(formData.password, publicKey.value),
    code: code.value,
    captcha: formData.captcha,
    publicKey: publicKey.value
  }
 loginApi(userlogin)
    .then(async (res) => {
...})
}

这里是直接使用加密,也可以封装成函数

基于 Vue 2 框架

安装 sm-crypto

你可以通过 npm 安装 sm-crypto:

npm install sm-crypto --save

封装 utils

'@/utils/smcrypto.js'

// utils.js

import smcrypto from 'sm-crypto';

    // SM2 加密
  export function  encrypt (plaintext, publicKey) {
        try {
            const cipherMode = 1; // 1 - C1C3C2,0 - C1C2C3
            const cipherText = smcrypto.sm2.doEncrypt(plaintext, publicKey, cipherMode);
            return cipherText;
        } catch (error) {
            console.error('SM2 encryption error:', error);
            return null;
        }
    }


在 Vue 组件中使用

在你的 Vue 组件中引入 smcrypto.js 并使用 encrypt方法:

import { encrypt } from '@/utils/smcrypto.js';

        // 获取加密私钥
        getPublicKey() {
            api.publicKey().then((res) => {
                this.param.rsaToken = res.data.rsaToken;
                this.rsaKey = res.data.rsaKey;
            });
        },

//登录请求参数

      let data = {
                        password: this.param.password,
                        username: this.param.username,
                        captchaCode: this.param.captchaCode,
                        captchaId: this.param.captchaId,
                        rsaToken: this.param.rsaToken,
                        // authCode: this.param.authCode,
                        checked: this.param.checked
                    };
                    data.password = encrypt(this.param.password, this.rsaKey);
//发起登录请求
//...

总结

到此这篇关于前端js sm2实现加密的文章就介绍到这了,更多相关前端 js sm2加密内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章