Examples of How to Derive a Signing Key for Signature Version 4 for Google Apps Script

Gists

This is a sample script for “Examples of How to Derive a Signing Key for Signature Version 4” using Google Apps Script.

In order to use AWS SDKs, there are the sample scripts for the languages of Java, .NET (C#), Python, Ruby, JavaScript (Node.js). But the sample script of Google Apps Script is not prepared. I saw the question related to this at Stackoverflow. So I would like to also introduce the sample script here.

In the sample scripts, the input values are as follows.

key = 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY'
dateStamp = '20120215'
regionName = 'us-east-1'
serviceName = 'iam'

From above values, the following value is required to be retrieved.

f4780e2d9f65fa895f9c67b32ce1baf0b0d8a43505a000a1a9e090d414db404d

In this report, above process is achieved with Google Apps Script.

Important points:

  • At Google Apps Script, the data which was encrypted by Utilities.computeHmacSha256Signature() is the bytes array of the signed hexadecimal. In the sample scripts, the bytes array is converted to the unsigned hexadecimal. So it is required to be converted.

    • But, when the byte array is created by Utilities.computeHmacSha256Signature(), the created byte array can be used for Utilities.computeHmacSha256Signature() without converting.

From above situation, the sample script for Google Apps Script can be made as follows.

Sample script:

function myFunction() {
  // These are the sample values of https://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html
  var key = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
  var dateStamp = "20120215";
  var regionName = "us-east-1";
  var serviceName = "iam";

  // I prepared the following script.
  var kDate = Utilities.computeHmacSha256Signature(dateStamp, "AWS4" + key);
  var kRegion = Utilities.computeHmacSha256Signature(
    Utilities.newBlob(regionName).getBytes(),
    kDate
  );
  var kService = Utilities.computeHmacSha256Signature(
    Utilities.newBlob(serviceName).getBytes(),
    kRegion
  );
  var kSigning = Utilities.computeHmacSha256Signature(
    Utilities.newBlob("aws4_request").getBytes(),
    kService
  );
  kSigning = kSigning
    .map(function(e) {
      return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2);
    })
    .join("");
  Logger.log(kSigning); // Result
}
  • About above script, for example, kDate is the byte array. So regionName is required to be converted to the byte array. Please be careful this.

Result:

When above script is run, the following value can be retrieved. This value is the same with the sample value.

f4780e2d9f65fa895f9c67b32ce1baf0b0d8a43505a000a1a9e090d414db404d

References: