cryptoUtil.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. let cryptoJs = require('crypto-js');
  2. let crypto = require('crypto');
  3. let config = require('../config/config');
  4. module.exports = {
  5. /**
  6. * 加盐加密
  7. *
  8. * @param {Object|String} data 需要加密的数据
  9. * @param {String} salt 盐
  10. * @return {String} 加密后的自负窜key
  11. */
  12. encrypt (data, salt) {
  13. if (typeof data === 'object') {
  14. try {
  15. data = JSON.stringify(data);
  16. } catch (error) {
  17. data = 'error_string_' + (+new Date())
  18. }
  19. }
  20. return cryptoJs.AES.encrypt(data + '', salt || config.salt);
  21. },
  22. /**
  23. * 加盐解密
  24. *
  25. * @param {String} data 加密过的密钥
  26. * @param {String} salt 加密时用的盐
  27. * @return {Object|String} 加密前数据
  28. */
  29. decrypt (data, salt) {
  30. let bytes = cryptoJs.AES.decrypt(data.toString(), salt || config.salt);
  31. try {
  32. data = JSON.parse(bytes.toString(cryptoJs.enc.Utf8));
  33. } catch (error) {
  34. data = bytes.toString(cryptoJs.enc.Utf8);
  35. }
  36. return data;
  37. },
  38. /**
  39. * generate an unique seed
  40. * @return {String} unique seed
  41. */
  42. seed: (function () {
  43. let seed = +new Date();
  44. return function () {
  45. return String(seed++);
  46. };
  47. })(),
  48. /**
  49. * generate a random string
  50. * @param {Number} length - length of the random string
  51. * @param {Boolean} onlyNum - whether the random string consists of only numbers
  52. * @param {Boolean} isComplex - whether the random string can contain complex chars
  53. * @return {String} generated random string
  54. */
  55. randString: (function () {
  56. let complexChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz!@#$%^&*()-=_+,./<>?;:[{}]\'"~`|\\';
  57. let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
  58. let numchars = '0123456789';
  59. return function (length, onlyNum, isComplex) {
  60. let strs = isComplex ? complexChars : chars;
  61. strs = onlyNum ? numchars : strs;
  62. length = length || 10;
  63. let ret = [];
  64. for (let i = 0, it; i < length; ++i) {
  65. it = Math.floor(Math.random() * strs.length);
  66. ret.push(strs.charAt(it));
  67. }
  68. return ret.join('');
  69. };
  70. })(),
  71. /**
  72. * md5 encryption
  73. * @param {String} content - content to be encrpted
  74. * @return {String} encryption
  75. */
  76. md5 (content) {
  77. return crypto
  78. .createHash('md5')
  79. .update(content)
  80. .digest('hex');
  81. },
  82. /**
  83. * generate an unique key
  84. * @return {String} unique key
  85. */
  86. uniqueKey () {
  87. let key = 'site' + this.seed() + this.randString(16);
  88. return this.md5(key);
  89. }
  90. };