简体   繁体   中英

Generating Amazon API signature in JavaScript, importing hash functions (jQuery)

As a preface, I am very new to JavaScript and web development. I apologize for any silly mistakes or misunderstandings I have!

I am making a widget for a web portal. The widgets are set up such that each one is an independent JavaScript function, so I have no access to the web page's HTML outside of my widget.

My current goal is to make API requests to Amazon, which requires a signature to be generated upon every request. I am using the following guide provided by Amazon:

http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-jscript

Unfortunately, since I do not have access to the web page's HTML, I am using the jQuery function $.getScript to import the function provided by the above Amazon guide:

code.google.com/p/crypto-js/#HMAC

Specifically, this one:

crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha256.js

My function currently looks like this:

/**
 *Get signature key by hashing, scheme provided by Amazon
 */
getSignatureKey: function(key, dateStamp, regionName, serviceName) {
  $.getScript("widgets/textshop/hmac-sha256.js", function(){
    return signatureKeyHelper();
  });
  //Helper function for getSignatureKey since getScript is returned immediately; function not loaded in time
  function signatureKeyHelper(){
    console.log("A");  //Outputs!
    var kDate= Crypto.HMAC(Crypto.SHA256, dateStamp, "AWS4" + key, { asBytes: true})
    console.log("B");  //Error in previous line!
    var kRegion= Crypto.HMAC(Crypto.SHA256, regionName, kDate, { asBytes: true });
    var kService=Crypto.HMAC(Crypto.SHA256, serviceName, kRegion, { asBytes: true });
    var kSigning= Crypto.HMAC(Crypto.SHA256, "aws4_request", kService, { asBytes: true });

    return kSigning;
  }
},

The console outputs "A", but gives the error "TypeError: Crypto.HMAC is not a function". The part I am very unsure of is the use of the "Crypto" name--I am completely stumped as to where this name came from, whether I should change it to something else, etc.

Thanks for your time!

Crypto is a library you would normally load on your page.

The error means the function has not been defined; i guess the $.getScript is not working as you intend it to.

note: you should never-ever expose publicly you AWS secret key. You can't encrypt on client side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM