@code-nl/shopify-hmac
Version:
Shopify HMAC lib to verify Shopify calls
48 lines (41 loc) • 1.11 kB
JavaScript
;
const crypto = require("crypto");
/**
* Test the equasion of 2 HMAC strings.
*
* @param {String} HMAC A
* @param {String} HMAC B
* @return {Bool}
*/
exports.hmacTimingSafeEqual = (hmacA, hmacB) => {
// guard: HMAC A and HMAC B are both required
if (typeof hmacA !== "string" || typeof hmacB !== "string") {
return false;
}
// init return value
let valid = false;
// init buffers
const hmacBufferA = Buffer.from(hmacA, "utf-8");
const hmacBufferB = Buffer.from(hmacB, "utf-8");
// make the equasion
try {
valid = crypto.timingSafeEqual(hmacBufferB, hmacBufferA);
} catch (e) {
valid = false;
}
return valid;
};
/**
* Sign a message with some private secret to get it's HMAC validation signature.
*
* @param {String} message The query as string
* @param {String} secret Secret used with encryption
* @param {String} digest The digest type of the output
* @return {String} Generated HMAC
*/
exports.getHmacFromString = (message, secret, digest) => {
return crypto
.createHmac("sha256", secret)
.update(message)
.digest(digest);
};