添加依赖:
npm install sm-crypto --save
生成公钥和私钥:
// 引入 sm2.js文件
const { publicKey, privateKey } = sm2.generateKeyPairHex();
sessionStorage.setItem("fpuk", pubKey); //公钥
sessionStorage.setItem("fprss", privKey);//私钥
或者
const sm2 = require('sm-crypto').sm2
let keypair = sm2.generateKeyPairHex();
// 公钥
let publicKey = keypair.publicKey.toUpperCase();
// 私钥
let privateKey = keypair.privateKey.toUpperCase();
公钥加密
// const sm2 = require('sm-crypto').sm2;
sm2.doEncrypt(data, publicKey);
私钥解密
// const sm2 = require('sm-crypto').sm2;
sm2.doDecrypt(data, privateKey);
let userName = sm2.doDecrypt(
sessionStorage.getItem("user"),
sessionStorage.getItem("fprss"),
1//(0:加密,1解密)
);