Front end of the Slack clone application.

getHashDigest.js 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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) throw new Error("Unknown encoding base" + base);
  15. const readLength = buffer.length;
  16. const Big = require("big.js");
  17. Big.RM = Big.DP = 0;
  18. let b = new Big(0);
  19. for(let i = readLength - 1; i >= 0; i--) {
  20. b = b.times(256).plus(buffer[i]);
  21. }
  22. let output = "";
  23. while(b.gt(0)) {
  24. output = encodeTable[b.mod(base)] + output;
  25. b = b.div(base);
  26. }
  27. Big.DP = 20;
  28. Big.RM = 1;
  29. return output;
  30. }
  31. function getHashDigest(buffer, hashType, digestType, maxLength) {
  32. hashType = hashType || "md5";
  33. maxLength = maxLength || 9999;
  34. const hash = require("crypto").createHash(hashType);
  35. hash.update(buffer);
  36. if(digestType === "base26" || digestType === "base32" || digestType === "base36" ||
  37. digestType === "base49" || digestType === "base52" || digestType === "base58" ||
  38. digestType === "base62" || digestType === "base64") {
  39. return encodeBufferToBase(hash.digest(), digestType.substr(4)).substr(0, maxLength);
  40. } else {
  41. return hash.digest(digestType || "hex").substr(0, maxLength);
  42. }
  43. }
  44. module.exports = getHashDigest;