前端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); //發(fā)起登錄請求 //...
總結
到此這篇關于前端js sm2實現加密的文章就介紹到這了,更多相關前端 js sm2加密內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
js獲取當前年月日時分秒的方法實例(new?Date()/moment.js)
JavaScript是一種流行的編程語言,它可以用來獲取當前年月日,這篇文章主要給大家介紹了關于js獲取當前年月日時分秒的相關資料,分別使用的是new?Date()/moment.js,需要的朋友可以參考下2024-07-07javascript下搜索子字符串的的實現代碼(腳本之家修正版)
由于我的項目中要求到要對一個字符串進行查找,其查找要求有點BT了2009-12-12