algos.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. const crypto = require('crypto');
  2. const moment = require('moment');
  3. const md5 = require('md5');
  4. const sha1 = require('sha1');
  5. function pad2(n) {
  6. return n < 10 ? '0' + n : n
  7. }
  8. /**
  9. * 微信指定的加密算法
  10. */
  11. function encrypt(obj, addtionalStr) {
  12. // sort fields alphabetically
  13. let keyArray = [];
  14. for (let key in obj) {
  15. if (obj.hasOwnProperty(key)) {
  16. keyArray.push(key);
  17. }
  18. }
  19. keyArray.sort((l, r) => {
  20. if (l > r) {
  21. return 1;
  22. } else if (l < r) {
  23. return -1;
  24. } else {
  25. throw new 'encrypted obj with same key: ' + l;
  26. }
  27. });
  28. let rawString = '';
  29. keyArray.forEach(key => {
  30. rawString += `${key}=${obj[key]}&`;
  31. });
  32. // remove last &
  33. rawString = rawString.substring(0, rawString.length - 1);
  34. if (addtionalStr) {
  35. rawString += addtionalStr;
  36. }
  37. return rawString;
  38. }
  39. let Base64Handler = {
  40. encryption: (str) => {
  41. return Buffer(str).toString('base64');
  42. },
  43. decrypt: (str) => {
  44. return Buffer(str, 'base64').toString();
  45. },
  46. timespan: () => {
  47. var date = new Date();
  48. return date.getFullYear().toString() + pad2(date.getMonth() + 1) + pad2(date.getDate()) + pad2(date.getHours()) + pad2(date.getMinutes()) + pad2(date.getSeconds());
  49. },
  50. genNowSeq: () => {
  51. return moment().format('YYYYMMDDHHmmssSSS');
  52. },
  53. getTimeStamp: () => {
  54. var date = new Date();
  55. return date.getFullYear().toString() + pad2(date.getMonth() + 1) + pad2(date.getDate()) + pad2(date.getHours()) + pad2(date.getMinutes()) + pad2(date.getSeconds());
  56. },
  57. genNonceStr: (number = 16) => {
  58. return crypto.randomBytes(number).toString('hex');
  59. },
  60. getClientIp: (req) => {
  61. let ip = req.ip;
  62. if (ip.substr(0, 7) === "::ffff:") {
  63. ip = ip.substr(7)
  64. }
  65. return ip;
  66. },
  67. /**
  68. * 生成n位随机数
  69. */
  70. creatRandomByNumber: (n) => {
  71. var rnd = "";
  72. for (var i = 0; i < n; i++) {
  73. rnd += Math.floor(Math.random() * 10);
  74. }
  75. return rnd;
  76. },
  77. encryptMd5: (obj, etcStr) => {
  78. return md5(encrypt(obj, etcStr)).toUpperCase();
  79. },
  80. encryptSha1: (obj, etcStr) => {
  81. return sha1(encrypt(obj, etcStr));
  82. }
  83. }
  84. module.exports = Base64Handler;