前端js sm2实现加密简单代码举例
作者: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);
//发起登录请求
//...总结
到此这篇关于前端js sm2实现加密的文章就介绍到这了,更多相关前端 js sm2加密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
