123456789101112131415161718192021222324252627282930 |
- // 引入 miniprogram-sm-crypto 库中的 SM2 模块
- const sm2 = require("miniprogram-sm-crypto").sm2;
- const cipherMode = 1 // 1 - C1C3C2,0 - C1C2C3,默认为1
- const publicKey = '04298364ec840088475eae92a591e01284d1abefcda348b47eb324bb521bb03b0b2a5bc393f6b71dabb8f15c99a0050818b56b23f31743b93df9cf8948f15ddb54'
- const privateKey = ''
- // SM2加密函数
- function sm2Encrypt(msgString) {
- let msg = msgString;
- // 检查传入的消息是否为字符串,如果不是字符串则转换为 JSON 字符串
- if (typeof msgString !== "string") {
- msg = JSON.stringify(msgString);
- }
- // 使用 SM2 加密算法对消息进行加密
- let encryptData = sm2.doEncrypt(msg, publicKey, cipherMode); // 加密结果
- return encryptData;
- }
-
- // SM2解密函数
- function sm2Decrypt(msgString) {
- // 使用 SM2 解密算法对消息进行解密
- let decryptData = sm2.doDecrypt(msgString, privateKey, cipherMode); // 解密结果
- return decryptData;
- }
-
- // 导出加密和解密函数
- module.exports = {
- sm2Encrypt,
- sm2Decrypt,
- };
|