Skip to content

Instantly share code, notes, and snippets.

@xeaone
Forked from agrueneberg/client.html
Last active August 21, 2018 01:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeaone/bcade2ad7191e6b6a7825afd9cdbd73b to your computer and use it in GitHub Desktop.
Save xeaone/bcade2ad7191e6b6a7825afd9cdbd73b to your computer and use it in GitHub Desktop.
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