Skip to content

Instantly share code, notes, and snippets.

@RobK
Last active January 28, 2022 10:03
Show Gist options
  • Save RobK/7036909 to your computer and use it in GitHub Desktop.
Save RobK/7036909 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);
}
);
@socketwiz
Copy link

When I run example.js I get an error:

403 '<AccessDeniedException>\n  <Message>Unable to determine service/operation name to be authorized</Message>\n</AccessDeniedException>\n'

I did replace the id and key with my own. Any ideas?

@iSkore
Copy link

iSkore commented Oct 14, 2016

Post your code but that's an IAM Access error - You're using a key that doesn't have permission to the ARN or the service itself

@danmcgill6
Copy link

I have spent hours looking for this answer thank you for posting this.

@PavithranRick
Copy link

Bro, Love from India. Cheers!

@VasuNIPL
Copy link

VasuNIPL commented Feb 8, 2021

Does the above code work in React-native?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment