getSM4.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import md5 from 'js-md5'
  2. const {
  3. SM4
  4. } = require('gm-crypto')
  5. export function encryptAndSign(appKey, appSecret, privateKey, content, crypt) {
  6. try {
  7. // 签名 appKey + appSecret + timestamp
  8. let timestamp = Date.now(); //时间戳
  9. let str = appKey + appSecret + timestamp
  10. const sign = md5(str);
  11. // console.log("签名结果:", sign);
  12. //加密
  13. let key = ""
  14. for (let i = 0; i < privateKey.length; i++) {
  15. key += privateKey.charCodeAt(i).toString(16);
  16. }
  17. let data = {
  18. sign,
  19. timestamp
  20. }
  21. if (crypt == "decrypt") {
  22. // 对数据进行解密 decrypt - 解密方法
  23. // var decrypted = SM4.decryptData_ECB(content)
  24. data.decrypted = SM4.decrypt(content, key, {
  25. inputEncoding: 'hex',
  26. outputEncoding: 'utf8'
  27. })
  28. // console.log("内容解密结果:" + data.decrypted);
  29. } else {
  30. // 对数据进行加密 encrypt - 加密方法
  31. data.encrypted = SM4.encrypt(content, key, {
  32. inputEncoding: 'utf8',
  33. outputEncoding: 'hex'
  34. })
  35. // console.log("内容加密结果:" + data.encrypted);
  36. }
  37. return data
  38. } catch (error) {
  39. return null
  40. }
  41. }
  42. module.exports = {
  43. encryptAndSign,
  44. };