1. /**
  2. * Hashes user data for non-production use with optional flags.
  3. *
  4. * @param {string} data The data to hash.
  5. * @param {string} [algorithm='sha256'] The hashing algorithm to use (e.g., 'md5', 'sha1', 'sha256', 'sha512'). Defaults to 'sha256'.
  6. * @param {boolean} [salt=true] Whether to include a salt. Defaults to true.
  7. * @param {string} [saltString='randomSalt'] The salt string to use. Defaults to 'randomSalt'.
  8. * @returns {string} The hashed data. Returns an empty string if data is invalid.
  9. */
  10. function hashData(data, algorithm = 'sha256', salt = true, saltString = 'randomSalt') {
  11. if (typeof data !== 'string' || data.length === 0) {
  12. return ""; // Handle invalid input
  13. }
  14. const crypto = require('crypto');
  15. let hash;
  16. try {
  17. let hashOptions = {};
  18. switch (algorithm.toLowerCase()) {
  19. case 'md5':
  20. hashOptions = { algorithm: 'md5' };
  21. break;
  22. case 'sha1':
  23. hashOptions = { algorithm: 'sha1' };
  24. break;
  25. case 'sha256':
  26. hashOptions = { algorithm: 'sha256' };
  27. break;
  28. case 'sha512':
  29. hashOptions = { algorithm: 'sha512' };
  30. break;
  31. default:
  32. console.warn(`Unknown algorithm: ${algorithm}. Defaulting to sha256.`);
  33. hashOptions = { algorithm: 'sha256' };
  34. }
  35. let hashValue;
  36. if (salt) {
  37. hashValue = crypto.createHash(algorithm, data + saltString).digest('hex');
  38. } else {
  39. hashValue = crypto.createHash(algorithm).update(data).digest('hex');
  40. }
  41. return hashValue;
  42. } catch (error) {
  43. console.error("Hashing error:", error);
  44. return ""; // Handle errors
  45. }
  46. }
  47. module.exports = hashData;

Add your comment