getHashDigest.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. const baseEncodeTables = {
  3. 26: 'abcdefghijklmnopqrstuvwxyz',
  4. 32: '123456789abcdefghjkmnpqrstuvwxyz', // no 0lio
  5. 36: '0123456789abcdefghijklmnopqrstuvwxyz',
  6. 49: 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ', // no lIO
  7. 52: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
  8. 58: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ', // no 0lIO
  9. 62: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
  10. 64: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_',
  11. };
  12. function encodeBufferToBase(buffer, base) {
  13. const encodeTable = baseEncodeTables[base];
  14. if (!encodeTable) {
  15. throw new Error('Unknown encoding base' + base);
  16. }
  17. const readLength = buffer.length;
  18. const Big = require('big.js');
  19. Big.RM = Big.DP = 0;
  20. let b = new Big(0);
  21. for (let i = readLength - 1; i >= 0; i--) {
  22. b = b.times(256).plus(buffer[i]);
  23. }
  24. let output = '';
  25. while (b.gt(0)) {
  26. output = encodeTable[b.mod(base)] + output;
  27. b = b.div(base);
  28. }
  29. Big.DP = 20;
  30. Big.RM = 1;
  31. return output;
  32. }
  33. function getHashDigest(buffer, hashType, digestType, maxLength) {
  34. hashType = hashType || 'md5';
  35. maxLength = maxLength || 9999;
  36. const hash = require('crypto').createHash(hashType);
  37. hash.update(buffer);
  38. if (
  39. digestType === 'base26' ||
  40. digestType === 'base32' ||
  41. digestType === 'base36' ||
  42. digestType === 'base49' ||
  43. digestType === 'base52' ||
  44. digestType === 'base58' ||
  45. digestType === 'base62' ||
  46. digestType === 'base64'
  47. ) {
  48. return encodeBufferToBase(hash.digest(), digestType.substr(4)).substr(
  49. 0,
  50. maxLength
  51. );
  52. } else {
  53. return hash.digest(digestType || 'hex').substr(0, maxLength);
  54. }
  55. }
  56. module.exports = getHashDigest;