欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

前端js?sm2實(shí)現(xiàn)加密簡(jiǎn)單代碼舉例

 更新時(shí)間:2024年09月26日 10:43:17   作者:luquinn  
在Vue項(xiàng)目中實(shí)現(xiàn)數(shù)據(jù)加密,首先需要安裝SM2加密庫(kù),如js-sm2或sm-crypto,通過(guò)npm或yarn進(jìn)行安裝后,在Vue組件或文件中引入該庫(kù),并使用其提供的加密、解密功能,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下

vue3

1. 安裝 SM2 加密庫(kù)

首先,你需要安裝適合的 SM2 加密庫(kù)。在前面的討論中提到了 js-sm2 這個(gè) JavaScript 實(shí)現(xiàn)的 SM2 加密算法庫(kù),你可以使用 npm 或者 yarn 進(jìn)行安裝

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

2. 引入 SM2 庫(kù)并使用

在 Vue 3 的項(xiàng)目中,一般來(lái)說(shuō)你會(huì)在需要加密的組件或者文件中引入 SM2 庫(kù),并使用其提供的加密、解密等功能。以下是一個(gè)簡(jiǎn)單的示例:

// 在需要加密的組件或者文件中引入
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) => {
...})
}

這里是直接使用加密,也可以封裝成函數(shù)

vue2

安裝 sm-crypto

你可以通過(guò) 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;
            });
        },

//登錄請(qǐng)求參數(shù)

      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);
//發(fā)起登錄請(qǐng)求
//...

總結(jié) 

到此這篇關(guān)于前端js sm2實(shí)現(xiàn)加密的文章就介紹到這了,更多相關(guān)前端 js sm2加密內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論