Skip to content

Instantly share code, notes, and snippets.

@vokeio vokeio/client.js forked from agrueneberg/client.html
Last active Aug 21, 2018

Embed
What would you like to do?
HMAC Signature Verification
const Http = require('http');
const Crypto = require('crypto');
const query = 'key=value';
const sharedSecret = 'secret';
const signature = Crypto.createHmac('sha256', sharedSecret).update(query).digest('hex');
Http.get({
port: 8000,
path: '/?' + query,
headers: {
'x-signature': signature
}
}, function (res) {
let data = '';
res.on('error', console.error);
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
console.log(res.statusCode);
console.log(data);
});
});
const Url = require('url');
const Http = require('http');
const Crypto = require('crypto');
const sharedSecret = 'secret';
Http.createServer(function (req, res) {
// Get signature
const retrievedSignature = req.headers['x-signature'];
// Recalculate signature
const parsedUrl = Url.parse(req.url);
const computedSignature = Crypto.createHmac('sha256', sharedSecret).update(parsedUrl.query).digest('hex');
// Compare signatures
const computedSignatureBuffer = Buffer.from(computedSignature, 'hex');
const retrievedSignatureBuffer = Buffer.from(retrievedSignature, 'hex');
// NOTE: might want to check length of buffers
const valid = Crypto.timingSafeEqual(computedSignatureBuffer, retrievedSignatureBuffer);
if (valid) {
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('valid');
} else {
res.writeHead(403, { 'content-type': 'text/plain' });
res.end('not valid');
}
}).listen(8000);
console.log('running on port 8000');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.