前端 js sm2实现加密

vue3

1. 安装 SM2 加密库

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

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

2. 引入 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) => {
...})
}

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

、、、、、、、、、、

vue2

安装 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);
//发起登录请求
//...

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值