簡體   English   中英

將C#轉換為Ruby-HMAC SHA256函數

[英]Convert C# to Ruby - HMAC SHA256 function

我試圖讓HMAC SHA256值(str_signature),我也跟着從這個Ruby代碼 ,雖然他的例子是從Java代碼轉換(用六角扳手)。

C#

string strRawSignature = "200123123891:12|11231231|GET|just%20test%20value"

// Convert signature to byte array in order to compute the hash
byte[] bSignature = Encoding.UTF8.GetBytes(strRawSignature);

// Convert ApiKey to byte array - for initializing HMACSHA256
byte[] bSecretKey = Convert.FromBase64String(strApiKey);

string strSignature = "";
using (HMACSHA256 hmac = new HMACSHA256(bSecretKey))
{
    // Compute signature hash
    byte[] bSignatureHash = hmac.ComputeHash(bSignature);

    // Convert signature hash to Base64String for transmission
    str_signature = Convert.ToBase64String(bSignatureHash);
}

紅寶石

require "openssl"
require "base64"

digest = OpenSSL::Digest.new('sha256')
key = [ 'xiIm9FuYhetyijXA2QL58TRlvhuSJ73FtdxiSNU2uHE=' ]

#this is just a dummy signature to show what the possible values are
signature = "200123123891:12|11231231|GET|just%20test%20value"

hmac = OpenSSL::HMAC.digest(digest, key.pack("m*"), signature)
str_signature = Base64.urlsafe_encode64(hmac)
example result: "B0NgX1hhW-rsnadD2_FF-grcw9pWghwMWgG47mU4J94="

更新:

  1. pack方法更改為輸出base64字符串。

  2. 編輯變量名以保持一致性

參考文獻:

  1. 用過的hexdigest ,具有不同的輸出字符串長度。
  2. 盡管我不確定key參數的值是多少,但本示例使用了digest方法,希望它是一個以64為基數的字符串。
  3. 再次使用hexdigest。 我非常確定摘要是對抗hexdigest的方法,因為hexdigest輸出與我從C#腳本獲得的示例HMAC值相比,具有更長的字符串。

終於得到了我的猴子!

畢竟,我真的不需要創建sha256摘要對象,只需要輸入'sha256'參數即可。

require 'openssl'
require "base64"
#API_KEY = base64 encoded string
key = Base64.decode64(API_KEY)
hash  = OpenSSL::HMAC.digest('sha256', key, "Message")
puts Base64.encode64(hash)

感謝這個鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM