secret.js 1.0 KB

123456789101112131415161718192021222324252627282930
  1. // 引入 miniprogram-sm-crypto 库中的 SM2 模块
  2. const sm2 = require("miniprogram-sm-crypto").sm2;
  3. const cipherMode = 1 // 1 - C1C3C2,0 - C1C2C3,默认为1
  4. const publicKey = '04298364ec840088475eae92a591e01284d1abefcda348b47eb324bb521bb03b0b2a5bc393f6b71dabb8f15c99a0050818b56b23f31743b93df9cf8948f15ddb54'
  5. const privateKey = ''
  6. // SM2加密函数
  7. function sm2Encrypt(msgString) {
  8. let msg = msgString;
  9. // 检查传入的消息是否为字符串,如果不是字符串则转换为 JSON 字符串
  10. if (typeof msgString !== "string") {
  11. msg = JSON.stringify(msgString);
  12. }
  13. // 使用 SM2 加密算法对消息进行加密
  14. let encryptData = sm2.doEncrypt(msg, publicKey, cipherMode); // 加密结果
  15. return encryptData;
  16. }
  17. // SM2解密函数
  18. function sm2Decrypt(msgString) {
  19. // 使用 SM2 解密算法对消息进行解密
  20. let decryptData = sm2.doDecrypt(msgString, privateKey, cipherMode); // 解密结果
  21. return decryptData;
  22. }
  23. // 导出加密和解密函数
  24. module.exports = {
  25. sm2Encrypt,
  26. sm2Decrypt,
  27. };