-
-
Save xeaone/bcade2ad7191e6b6a7825afd9cdbd73b to your computer and use it in GitHub Desktop.
HMAC Signature Verification
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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