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加密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源链接:https://www.jb51.net/javascript/327997m0g.htm
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END











暂无评论内容