如何按 AWS 调用的字节顺序对列表进行排序

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

正在看 http://associates-amazon.s3.amazonaws.com/signed-requests/helper/index.html

以下名称-值对:

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

应该导致

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

如何在 R 中实现这一点?

据我所知,它们是按 as.numeric(charToRaw(name)) 值。如果第一个值相等,则按第二个值排序,然后是第三个值,依此类推。

问题:如何在 R 中执行此操作?

# 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"
)

获取字节数:

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

计算字节并绑定值

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

按第一列排序名称,然后按第二列、第三列...依此类推

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

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

所以最后 nvp[do.call(order, as.list(b))] returns 在正确排序的列表中

以上来自@Floo0 的答案非常好,与来自 this answer.

的加密签名结合使用时更加有用

直到找到这两个帖子,我才被卡住了。我用亚马逊的 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) 签名:

library(digest)
library(RCurl)

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

另外,我还没有用过,不过有一个Python moduleamazon-product-api,好像比较少用