最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

vue3

1. 安裝 SM2 加密庫

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

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

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

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;
            });
        },

//登錄請求參數(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ā)起登錄請求
//...

總結(jié) 

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

相關(guān)文章

最新評論

松桃| 布尔津县| 东方市| 囊谦县| 凌云县| 平乐县| 青神县| 从化市| 庐江县| 开原市| 景宁| 镇赉县| 宁城县| 武邑县| 乐都县| 灵台县| 临洮县| 宁化县| 本溪| 清苑县| 祁东县| 新平| 临颍县| 井陉县| 弋阳县| 禄丰县| 江永县| 卓尼县| 鹤山市| 德江县| 二手房| 高邮市| 马龙县| 交城县| 翼城县| 德化县| 平顶山市| 手机| 伊宁县| 太保市| 濮阳市|