How to sort a list by byte-order for AWS-Calls

2020-02-13 03:37发布

Having a look at http://associates-amazon.s3.amazonaws.com/signed-requests/helper/index.html

The following Name-Value Pairs:

Service=AWSECommerceService
Version=2011-08-01
AssociateTag=PutYourAssociateTagHere
Operation=ItemSearch
SearchIndex=Books
Keywords=harry+potter
Timestamp=2015-09-26T14:10:56.000Z
AWSAccessKeyId=123

The name-value pairs have been sorted according to byte-order

Should result in

AWSAccessKeyId=123
AssociateTag=PutYourAssociateTagHere
Keywords=harry%20potter
Operation=ItemSearch
SearchIndex=Books
Service=AWSECommerceService
Timestamp=2015-09-26T14%3A10%3A56.000Z
Version=2011-08-01

How to achieve this in R?

As far as i can tell they are sorted by their as.numeric(charToRaw(name)) values. If the first value is equal then they are sorted by the second one, then the third and so on.

Question: How to do this in R?

2条回答
Rolldiameter
2楼-- · 2020-02-13 04:24
# Name-Value-Pairs
nvp <- list(                                
"Service"="AWSECommerceService",
"Version"="2011-08-01",
"AssociateTag"="PutYourAssociateTagHere",
"Operation"="ItemSearch",
"SearchIndex"="Books",
"Keywords"="harry potter",
"Timestamp"="2015-09-26T14:10:56.000Z",
"AWSAccessKeyId"="123"
)

Get Bytes:

bytes <- function(chr){
  as.data.frame(t(as.numeric(charToRaw(chr))))
}

Calculate Bytes, and rbind the values

b <- lapply(names(nvp), bytes)
b <- data.table::rbindlist(b, fill=TRUE) # other than base::rbind, this fills by NA

Order the names by first column, then by second, by third, ... and so on

names(nvp)[do.call(order, as.list(b))]

[1] "AWSAccessKeyId" "AssociateTag"   "Keywords"       "Operation"      "SearchIndex"   
[6] "Service"        "Timestamp"      "Version"   

So finally nvp[do.call(order, as.list(b))] returns in the properly sorted list

查看更多
The star\"
3楼-- · 2020-02-13 04:27

The answer above from @Floo0 is very good and is even more useful when combined with the encrypted signature from this answer.

I was stuck until I found these two posts. I used Amazon's Signed Request Helper to verify that I successfully signed my query. Use the code above to properly canonically sort the query and this code (again found here) to sign it:

library(digest)
library(RCurl)

curlEscape(
  base64(
         hmac(enc2utf8((secret_key)), 
              enc2utf8(string_to_sign), 
              algo = 'sha256', 
              serialize = FALSE,  
               raw = TRUE)
          )
         )  

Also, I have not used it yet, but there is a Python module, amazon-product-api, that seems to be less work.

查看更多
登录 后发表回答