将C#转换为Ruby - HMAC SHA256函数

时间:2015-08-20 04:06:26

标签: c# ruby

我正在尝试获取HMAC SHA256值(str_signature),我遵循了此post中的Ruby代码,尽管他的示例是从Java转换代码(使用Hex键)。

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 method更改为输出base64字符串。

  2. 编辑了一致性变量名称

  3. 参考文献:

    1. 使用hexdigest,具有不同的输出字符串长度。
    2. 这个example使用digest方法,虽然我不确定key参数的值是多少,但希望它是一个基本的64位编码字符串。
    3. This再次使用hexdigest。我很确定digest是与hexdigest相比的方法,因为与我从C#脚本获得的样本HMAC值相比,hexdigest输出的字符串更长。

1 个答案:

答案 0 :(得分:0)

终于得到了我背后的猴子!

我毕竟不需要创建一个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)

感谢这个format