前端js?sm2實(shí)現(xiàn)加密簡(jiǎn)單代碼舉例
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)文章
uploadify插件實(shí)現(xiàn)多個(gè)圖片上傳并預(yù)覽
這篇文章主要為大家詳細(xì)介紹了uploadify插件實(shí)現(xiàn)多個(gè)圖片上傳并預(yù)覽,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09表現(xiàn)、結(jié)構(gòu)、行為分離的選項(xiàng)卡效果
2008-01-01js獲取當(dāng)前年月日時(shí)分秒的方法實(shí)例(new?Date()/moment.js)
JavaScript是一種流行的編程語(yǔ)言,它可以用來(lái)獲取當(dāng)前年月日,這篇文章主要給大家介紹了關(guān)于js獲取當(dāng)前年月日時(shí)分秒的相關(guān)資料,分別使用的是new?Date()/moment.js,需要的朋友可以參考下2024-07-07javascript下搜索子字符串的的實(shí)現(xiàn)代碼(腳本之家修正版)
由于我的項(xiàng)目中要求到要對(duì)一個(gè)字符串進(jìn)行查找,其查找要求有點(diǎn)BT了2009-12-12JavaScript實(shí)現(xiàn)選中文字提示新浪微博分享效果
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)選中文字提示新浪微博分享效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06關(guān)于微信jssdk實(shí)現(xiàn)多圖片上傳的一點(diǎn)心得分享
這篇文章主要介紹了關(guān)于微信jssdk實(shí)現(xiàn)多圖片上傳的一點(diǎn)心得分享,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-12-12