HMAC Product Verification With Node.js

I successfully translated the PHP algorithm to validate product attributes into Node.js and it is working perfectly! I wanted to share the code in case somebody else is using a Node.js environment. I can also export this to an NPM package that you can just "require" in your projects.

var createHmac = require('crypto').createHmac;

module.exports = function hmacValidate(secret, key, value, productCode, parentCode = '', encodeValue = false) {
let hmac = createHmac('sha256', secret);
let toEncode = escapeHtml(productCode + parentCode + key + value);
let label = encodeValue ? value : key;
hmac.update(toEncode);
let result = label + '||' + hmac.digest('hex').toLowerCase();
if(value === '--OPEN--') {
result += '||open';
}
return result;
};

function escapeHtml(text) {
var map = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#039;'
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

Tagged:
Comments
Sign In or Register to comment.