-
-
Save dimorphic/5927918540792a28b3c4dbe9bfa8aaff to your computer and use it in GitHub Desktop.
Generating AWS HMAC in Nodejs (RFC 2104 compliant HMAC)
This file contains 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
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); |
This file contains 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
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