Skip to content

Instantly share code, notes, and snippets.

@maisnamraju
Forked from agrueneberg/client.html
Last active February 25, 2020 10:03
Show Gist options
  • Save maisnamraju/e3a51fed982284d1df310a4135f66e03 to your computer and use it in GitHub Desktop.
Save maisnamraju/e3a51fed982284d1df310a4135f66e03 to your computer and use it in GitHub Desktop.
HMAC-SHA256 sample code.
var http, crypto, sharedSecret, query, signature;
http = require("http");
crypto = require("crypto");
sharedSecret = "super-secret";
body = { "test": "123" };
signature = crypto.createHmac("sha256", sharedSecret).update(body).digest("hex");
http.post({
path: "localhost:1337/request",
body: body
headers: {
"X-Signature": signature
}
}, function (res) {
console.log(res.statusCode);
});
var http, url, crypto, sharedSecret;
http = require("http");
url = require("url");
crypto = require("crypto");
sharedSecret = "super-secret";
http.createServer(function (req, res) {
var retrievedSignature, parsedUrl, computedSignature;
// Deal with CORS.
res.setHeader("Access-Control-Allow-Origin", "*");
retrievedSignature = req.headers["x-signature"];
// Recalculate signature.
parsedUrl = url.parse(req.url);
computedSignature = crypto.createHmac("sha256", sharedSecret).update(req.body).digest("hex");
// Compare signatures.
if (computedSignature === retrievedSignature) {
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end("Hello World\n");
} else {
res.writeHead(403, {
"Content-Type": "text/plain"
});
res.end("Get Out\n");
}
}).listen(1337);
console.log("Server running on port 1337");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment