/**
* Hashes a value with optional flags for sandbox usage.
*
* @param {string} value The value to hash.
* @param {object} flags Optional flags.
* @param {string} flags.algorithm The hashing algorithm to use (md5, sha1, sha256). Defaults to sha256.
* @param {boolean} flags.hexOutput Whether to return the hex representation. Defaults to true.
* @returns {string} The hashed value.
* @throws {Error} If an invalid algorithm is specified.
*/
function sandboxHash(value, flags = {}) {
const algorithm = flags.algorithm || 'sha256';
const hexOutput = flags.hexOutput !== false; // Default to true
const hash = typeof crypto !== 'undefined' ? crypto.createHash(algorithm) : require('crypto').createHash(algorithm);
hash.update(value);
let hashValue = hash.digest(hexOutput ? 'hex' : 'binary');
return hashValue;
}
//Example Usage:
// const myValue = "some data";
// const hashedValue = sandboxHash(myValue); // Defaults to sha256, hex output
// console.log(hashedValue);
// const hashedValueSha1 = sandboxHash(myValue, { algorithm: 'sha1' });
// console.log(hashedValueSha1);
// const hashedValueBinary = sandboxHash(myValue, { hexOutput: false });
// console.log(hashedValueBinary);
// throws error
// try {
// const hashedValueInvalid = sandboxHash(myValue, {algorithm: 'invalid'});
// } catch (e) {
// console.error(e);
//}
Add your comment