getHashDigest.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. let createMd4 = undefined;
  34. let BatchedHash = undefined;
  35. function getHashDigest(buffer, hashType, digestType, maxLength) {
  36. hashType = hashType || 'md4';
  37. maxLength = maxLength || 9999;
  38. let hash;
  39. try {
  40. hash = require('crypto').createHash(hashType);
  41. } catch (error) {
  42. if (error.code === 'ERR_OSSL_EVP_UNSUPPORTED' && hashType === 'md4') {
  43. if (createMd4 === undefined) {
  44. createMd4 = require('./hash/md4');
  45. if (BatchedHash === undefined) {
  46. BatchedHash = require('./hash/BatchedHash');
  47. }
  48. }
  49. hash = new BatchedHash(createMd4());
  50. }
  51. if (!hash) {
  52. throw error;
  53. }
  54. }
  55. hash.update(buffer);
  56. if (
  57. digestType === 'base26' ||
  58. digestType === 'base32' ||
  59. digestType === 'base36' ||
  60. digestType === 'base49' ||
  61. digestType === 'base52' ||
  62. digestType === 'base58' ||
  63. digestType === 'base62'
  64. ) {
  65. return encodeBufferToBase(hash.digest(), digestType.substr(4)).substr(
  66. 0,
  67. maxLength
  68. );
  69. } else {
  70. return hash.digest(digestType || 'hex').substr(0, maxLength);
  71. }
  72. }
  73. module.exports = getHashDigest;