Amazon API Signature Algorithm (version Golang and Java edition)

Source: Internet
Author: User
Tags dateformat hmac sprintf
This is a creation in Article, where the information may have evolved or changed.

Package Mainimport "FMT" import "Crypto/hmac" import "crypto/sha256" import "Time" import "strings" Import encoding/ Base64 "Import" net/http "import" Net/url "import" io/ioutil "Const METHOD =" GET "Const HOST =" Webservices.amazon.com " Const uri= "/onca/xml" Const query_string= "awsaccesskeyid=121212121212&associatetag=smasholab-20&idtype= isbn&itemid=b000mqtjw2&operation=itemlookup&service=awsecommerceservice&timestamp=%s "Func Main ( ) {T: = time. Now () tm:= T.format ("2006-01-02t15:04:05z") tm= URL. Queryescape (tm) FMT. PRINTLN ("TM:", tm) Query: = FMT. Sprintf (Query_string, TM) UL: = FMT. Sprintf (Query_string, TM) FMT. PRINTLN ("Query:", "Query")//awsaccesskeyid: = "SSSBBBSSSBBB" Awssecretkeyid: = "Ooxxooxx" sha256: = sha256. Newhash: = HMAC. New (SHA256, []byte (Awssecretkeyid)) template:= "%s\n%s\n%s\n%s" template= fmt. Sprintf (template, METHOD, HOST, URI, query) fmt. Println ("Template:", template) hash. Write ([]byte (Template)) Sha: = base64. Stdencoding.encodetostring (hash. Sum (nil)) sha= URL. Queryescape(SHA) fmt. Println ("Sha", Sha) ul= ul + "&signature=" +shaul= "Http://webservices.amazon.com/onca/xml?" + UL ul= strings. Replace (UL, "+", "%20",-1) ul= strings. Replace (UL, "*", "%2a",-1) ul= strings. Replace (UL, "%7e", "~",-1) fmt. Println ("URL:", ul)//requestresponse, err: = http. Get (UL) if err! = Nil {fmt. Println ("Err", err)}else{content, _: = Ioutil. ReadAll (response. Body) println ("Response", string (content)) response. Body.close ()}}


------------------------The following is the Java version, a little verbose point----------------------------------


Package Com.amazon.associates.sample;import Java.io.unsupportedencodingexception;import Java.net.URLDecoder; Import Java.net.urlencoder;import Java.security.invalidkeyexception;import java.security.NoSuchAlgorithmException ; Import Java.text.dateformat;import java.text.simpledateformat;import java.util.calendar;import java.util.HashMap; Import Java.util.iterator;import java.util.map;import Java.util.sortedmap;import Java.util.timezone;import Java.util.treemap;import Javax.crypto.mac;import Javax.crypto.spec.secretkeyspec;import Org.apache.commons.codec.binary.base64;public class Signedrequestshelper {private static final String Utf8_charset = "U  TF-8 ";  private static final String Hmac_sha256_algorithm = "HmacSHA256";  private static final String Request_uri = "/onca/xml";  private static final String Request_method = "GET"; Private String endpoint = "webservices.amazon.com";  Must be lowercase private String Awsaccesskeyid = "YOUR AWS ACCESS KEY"; Private String Awssecretkey = "YOUR AWS SECRET KEY ";  Private Secretkeyspec secretkeyspec = null;  Private Mac Mac = null;    Public Signedrequestshelper () {byte[] secretykeybytes = awssecretkey.getbytes (Utf8_charset);    Secretkeyspec = new Secretkeyspec (secretykeybytes, hmac_sha256_algorithm);    Mac = Mac.getinstance (hmac_sha256_algorithm);  Mac.init (SECRETKEYSPEC);    Public String sign (map<string, string> params) {params.put ("Awsaccesskeyid", Awsaccesskeyid);    Params.put ("Timestamp", Timestamp ());    sortedmap<string, string> sortedparammap = new treemap<string, string> (params);    String Canonicalqs = canonicalize (Sortedparammap);    String tosign = request_method + "\ n" + endpoint + "\ n" + Request_uri + "\ n" + Canonicalqs;    String HMAC = HMAC (tosign);    String sig = percentEncodeRfc3986 (HMAC);    String url = "http://" + endpoint + Request_uri + "?" + Canonicalqs + "&signature=" + sig;  return URL; } private String HMAC (String stringtosign){String signature = null;    byte[] data;    Byte[] Rawhmac;      try {data = Stringtosign.getbytes (Utf8_charset);      Rawhmac = mac.dofinal (data);      BASE64 encoder = new Base64 ();    Signature = new String (Encoder.encode (RAWHMAC));    } catch (Unsupportedencodingexception e) {throw new RuntimeException (Utf8_charset + "is unsupported!", e);  } return signature;    private string Timestamp () {string timestamp = null;    Calendar cal = Calendar.getinstance ();    DateFormat DFM = new SimpleDateFormat ("Yyyy-mm-dd ' T ' HH:mm:ss ' Z ');    Dfm.settimezone (Timezone.gettimezone ("GMT"));    timestamp = Dfm.format (Cal.gettime ());  return timestamp; } private String canonicalize (sortedmap<string, string> sortedparammap) {if (Sortedparammap.isempty ()) {RE    Turn "";    } stringbuffer buffer = new StringBuffer ();    Iterator<map.entry<string, string>> iter = Sortedparammap.entryset (). Iterator (); while (Iter.hasnext ()) {Map.entry<string, string> Kvpair = Iter.next ();      Buffer.append (percentEncodeRfc3986 (Kvpair.getkey ()));      Buffer.append ("=");      Buffer.append (percentEncodeRfc3986 (Kvpair.getvalue ()));      if (Iter.hasnext ()) {Buffer.append ("&");    }} String canonical = Buffer.tostring ();  return canonical;    } private String percentEncodeRfc3986 (string s) {string out; try {out = Urlencoder.encode (S, utf8_charset). Replace ("+", "%20"). Replace ("*", "%2a"). Replace ("%7e    ", "~");    } catch (Unsupportedencodingexception e) {out = s;  } return out; }}




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.