Generate a HMAC Signature
JS
S
JavaScriptSimple snippet of how to create a simple HMAC signature. Please do use `async await` as crypto operations may take a while.
1const crypto = require('crypto');
2const moment = require('moment');
3const uuid = require('uuid');
4
5const generateSignature = async () => {
6 const hmac = crypto.createHmac('sha256', process.env.secretKey);
7 const timestamp = `${moment().unix()}`;
8 const nonce = uuid(); // arbitrary number to be used once
9 const requestMethod = 'POST';
10 const hashString = `${process.env.websiteKey}${requestMethod}${timestamp}${nonce}`;
11 try {
12 hmac.update(simpleHash)
13 } catch (err) {
14 throw err;
15 }
16 const requestHash = hmac.digest('base64')
17 return requestHash;
18 return [
19 process.env.websiteKey,
20 requestHash,
21 nonce,
22 timestamp
23 ].join(':')
24};
25
26// Alternative
27const crypto = require('crypto');
28const qs = require('qs');
29
30const getMessageSignature = (path, request, secret, nonce) => {
31 const message = qs.stringify(request);
32 const secret_buffer = new Buffer(secret, 'base64');
33 const hash = new crypto.createHash('sha256');
34 const hmac = new crypto.createHmac('sha512', secret_buffer);
35 const hash_digest = hash.update(nonce + message).digest('binary');
36 const hmac_digest = hmac.update(path + hash_digest, 'binary').digest('base64');
37
38 return hmac_digest;
39};
40Created on 2/22/2019