1. /**
  2. * Hashes a value with optional flags for sandbox usage.
  3. *
  4. * @param {string} value The value to hash.
  5. * @param {object} flags Optional flags.
  6. * @param {string} flags.algorithm The hashing algorithm to use (md5, sha1, sha256). Defaults to sha256.
  7. * @param {boolean} flags.hexOutput Whether to return the hex representation. Defaults to true.
  8. * @returns {string} The hashed value.
  9. * @throws {Error} If an invalid algorithm is specified.
  10. */
  11. function sandboxHash(value, flags = {}) {
  12. const algorithm = flags.algorithm || 'sha256';
  13. const hexOutput = flags.hexOutput !== false; // Default to true
  14. const hash = typeof crypto !== 'undefined' ? crypto.createHash(algorithm) : require('crypto').createHash(algorithm);
  15. hash.update(value);
  16. let hashValue = hash.digest(hexOutput ? 'hex' : 'binary');
  17. return hashValue;
  18. }
  19. //Example Usage:
  20. // const myValue = "some data";
  21. // const hashedValue = sandboxHash(myValue); // Defaults to sha256, hex output
  22. // console.log(hashedValue);
  23. // const hashedValueSha1 = sandboxHash(myValue, { algorithm: 'sha1' });
  24. // console.log(hashedValueSha1);
  25. // const hashedValueBinary = sandboxHash(myValue, { hexOutput: false });
  26. // console.log(hashedValueBinary);
  27. // throws error
  28. // try {
  29. // const hashedValueInvalid = sandboxHash(myValue, {algorithm: 'invalid'});
  30. // } catch (e) {
  31. // console.error(e);
  32. //}

Add your comment