diff options
Diffstat (limited to 'lib/utils.js')
-rw-r--r-- | lib/utils.js | 29 |
1 files changed, 24 insertions, 5 deletions
diff --git a/lib/utils.js b/lib/utils.js index 037d3236c..c76d31500 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -108,19 +108,38 @@ exports.anonymizeIp = function anonymizeIp(ip) { } }; +function objectToHashableString(object) { + // See https://stackoverflow.com/questions/899574/which-is-best-to-use-typeof-or-instanceof/6625960#6625960 + return (typeof(object) === 'string') ? object : JSON.stringify(object); +} + +const DefaultHash = 'Compiler Explorer Default Version 1'; + +/*** + * Gets the hash (as a binary buffer) of the given object + * + * Limitation: object shall not have circular references + * @param object {*} Object to get hash from + * @param HashVersion {String} Hash "version" + * @returns {Buffer} Hash of object + */ +exports.getBinaryHash = function getHash(object, HashVersion = DefaultHash) { + return crypto.createHmac('sha256', HashVersion) + .update(objectToHashableString(object)) + .digest('buffer'); +}; + /*** - * Gets the hash of the given object + * Gets the hash (as a hex string) of the given object * * Limitation: object shall not have circular references * @param object {*} Object to get hash from * @param HashVersion {String} Hash "version" * @returns {String} Hash of object */ -exports.getHash = function getHash(object, HashVersion = 'Compiler Explorer Default Version 1') { - // See https://stackoverflow.com/questions/899574/which-is-best-to-use-typeof-or-instanceof/6625960#6625960 - const asString = (typeof(object) === 'string') ? object : JSON.stringify(object); +exports.getHash = function getHash(object, HashVersion = DefaultHash) { return crypto.createHmac('sha256', HashVersion) - .update(asString) + .update(objectToHashableString(object)) .digest('hex'); }; |