1

我正在使用 ApiAuth gem(如在此处找到)来签署我的请求。我还在使用 CryptoJS(如在此处找到)编写自己的 JavaScript 代码,通过检查 ApiAuth 生成的加密标头与我的代码生成的标头来提供身份验证。

下面给出了来自 ApiAuth Gem 的代码片段:

def hmac_signature(headers, secret_key, options)
  if options[:with_http_method]
    canonical_string = headers.canonical_string_with_http_method(options[:override_http_method])
  else
    canonical_string = headers.canonical_string
  end
  digest = OpenSSL::Digest.new('sha1')
  b64_encode(OpenSSL::HMAC.digest(digest, secret_key, canonical_string))
end

这是我用 JavaScript 编写的等效代码:

function hmacSignature(request, appSecret) {
 return CryptoJS.HmacSHA1(canonicalString(request), appSecret).toString(CryptoJS.enc.Base64);}

这两个不会生成相同的加密标头。我尝试使用 jsSHA 来做同样的事情,虽然 jsSHA 和 CryptoJS 生成的加密标头是相同的,但它们与 ApiAuth 生成的标头不匹配。

请帮我弄清楚如何使这项工作。

编辑:

将 Canonical String 作为“消息”并将 appSecret 作为“secret”,我从 ApiAuth 和 CryptoJS 获得相同的值,即:

DK9kn+7klT2Hv5A6wRdsReAo3xY=

我发现我的原始代码中的问题即将出现,因为我的 JS 代码中设置的时间戳和 ApiAuth 中设置的时间戳不匹配。

4

1 回答 1

0

I fixed my problem and am writing this answer in hopes that it helps someone else looking for a solution to this problem.

  1. Let me start off by saying that the two encryptions should be the same whether they are encrypted in Ruby or JS or any other language.
  2. It is important to check that every portion of the input sent to both places is exactly the same and completely identical.

When I checked my inputs to the JS file and the gem, I realised that for some reason the time-stamp (which I was setting in the JS file) wasn't getting sent correctly to the gem.

I debugged my code step by step and figured out where the mistake was. I am outlining some of the possible issues below:

  1. I was setting the timestamp in my JS as follow

    request.headers["DATE"]

I realised that this wasn't getting set correctly so I had to change "DATE" to "DATE1" and accordingly change the rest of my code. This worked.

  1. Second, the timestamp I was sending wasn't compatible with the HTTP GST type timestamp that was expected by the gem. This is another thing that you must keep in mind when sending the timestamp.
于 2016-05-10T03:34:36.007 回答