亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

前端js?sm2實現加密簡單代碼舉例

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

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

總結 

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

相關文章

最新評論