1.jsencrypt 公钥私钥随便找个网站生成(https://www.bejson.com/enc/rsa/)
1.安装包:npm i jsencrypt --save
2.封装函数
import { JSEncrypt } from 'jsencrypt';
// 加密 msg为需要加密的字符串,返回加密后的字符串
export function setEncrypt(msg) {
const jsencrypt = new JSEncrypt();
jsencrypt.setPublicKey('公钥');
return jsencrypt.encrypt(msg);
}
// 解密 msg为加密后的字符串,返回解密返回的字符串
export function decrypt(msg) {
const decrypt = new JSEncrypt();
decrypt.setPrivateKey('私钥');
const decryptMsg = decrypt.decrypt(msg);
return decryptMsg;
}
2.sm-crypto
1.安装包: npm i sm-crypto --save
2.封装函数
import { sm2 } from 'sm-crypto';
const keypair = sm2.generateKeyPairHex()
//可生成一对公私钥(生成后写死调用)
const publicKey = keypair.publicKey // 公钥
const privateKey = keypair.privateKey // 私钥
const PBLICKEY = '041a9f945535fb9be8f9ae11299a82baa99762ebdea672a902c85c986d70fd4b8dc841b062ff0cf964a930ae4a0ac3cedbaf1f46f983f60d3bb68f3f27a89a8b7c'
const PRIVATEKEY = '16e73c8c3646d7d724efb8fa56e2616da6a824ae81ad6c91026b2a05d1c2d0e1'
// 加密
export function setEncrypt(msg) {
const pubKey = `${PBLICKEY}`; // 公钥
const cipherMode = 1; // 1 - C1C3C2,0 - C1C2C3,默认为1
const encryptData = sm2.doEncrypt(msg, pubKey, cipherMode); // 加密结果
return encryptData;
}
// 解密
export function decrypt(msg) {
const priKey = `${PRIVATEKEY}`; // 私钥
const cipherMode = 1; // 1 - C1C3C2,0 - C1C2C3,默认为1
const decryptData = sm2.doDecrypt(msg, priKey, cipherMode); // 解密结果
return decryptData;
}
标签:const,url,decrypt,加解密,crypto,sm,msg,jsencrypt
From: https://www.cnblogs.com/songkomei/p/17314872.html