diff options
author | Matt Godbolt <matt@godbolt.org> | 2018-08-18 10:02:28 -0500 |
---|---|---|
committer | Matt Godbolt <matt@godbolt.org> | 2018-08-18 10:02:28 -0500 |
commit | 08cd1edc69ba1c6707c35b1de85a30e700fae00c (patch) | |
tree | 9f167eaaa9606fcec7224719b1468a9a4247c631 /lib/utils.js | |
parent | 2d23accb8707a4942ca8ce456cb5b14b36a040dd (diff) | |
download | compiler-explorer-08cd1edc69ba1c6707c35b1de85a30e700fae00c.tar.gz compiler-explorer-08cd1edc69ba1c6707c35b1de85a30e700fae00c.zip |
Use binary buffers for hash; safe64 encode results. Addresses #1056
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'); }; |