Skip to content

Instantly share code, notes, and snippets.

@robmcalister
Forked from RobK/core.js
Created October 18, 2017 03:35
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 robmcalister/d6cf79ce8f74e25cad2869a59b6c8aae to your computer and use it in GitHub Desktop.
Save robmcalister/d6cf79ce8f74e25cad2869a59b6c8aae to your computer and use it in GitHub Desktop.
NodeJS example code to generate a RFC 2104 compliant HMAC
var crypto = require("crypto");
/**
* Get the signature/digest of a supplied input string
* @param data [Required] The String to encode
* @param awsSecretKey [Required] Secret key shared with Amazon
* @param algorithm [Optional] Encryption algorithm, defaults to sha256
* @param encoding [Optional] The output encoding. Default to base64
* @returns Str with encoded digest of the input string
*/
function generateHmac (data, awsSecretKey, algorithm, encoding) {
encoding = encoding || "base64";
algorithm = algorithm || "sha256";
return crypto.createHmac(algorithm, awsSecretKey).update(data).digest(encoding);
}
var d = new Date();
var rfc2104Hmac = generateHmac(d.toUTCString(), "awsSecretKey value");
console.log(rfc2104Hmac);
var request = require("request");
var crypto = require("crypto");
var d = new Date().toUTCString();
var config = {
awsAccessKeyId : "AWS key",
awsSecretKey : "AWS Secret"
}
// Options for the http POST request
var options = {
"headers" : {
"Date" : d, // Must pass the Date header as well as the X-Amzn-Authorization header
"X-Amzn-Authorization" : "AWS3-HTTPS AWSAccessKeyId=" + config.awsAccessKeyId +
",Algorithm=HMACSHA256,Signature=" + generateHmac(d, config.awsSecretKey)
},
"form" : {
}
};
function generateHmac (data, awsSecretKey, algorithm, encoding) {
encoding = encoding || "base64";
algorithm = algorithm || "sha256";
return crypto.createHmac(algorithm, awsSecretKey).update(data).digest(encoding);
}
request.post(
"https://email.us-east-1.amazonaws.com/",
options,
function (error, response, body) {
console.log(response.statusCode, body);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment