Ruby HMAC signing issue

有些话、适合烂在心里 提交于 2019-12-11 06:01:11

问题


I got an issue with HMAC. I have to sign a form before sending it to a bank. They only provide an example in PHP in their documentation.

I have a hex key to sign my data (e.g. FCEBA61A884A938E7E7FE4F5C68AA7F4A349768EE5957DDFBE99C1D05A09CBACF1FCF0A7084CB2E4CBA95193176C4395DE7F39EA9DBEBEF0907D77192AAE3E8A).

In the PHP exemple, they do this with the key before signing the data:

 $key = "FCEBA61A884A938E7E7FE4F5C68AA7F4A349768EE5957DDFBE99C1D05A09CBACF1FCF0A7084CB2E4CBA95193176C4395DE7F39EA9DBEBEF0907D77192AAE3E8A";
 $message = "param1=a&param2=b";

 $binKey = pack('H*', $key);
 $signature = hash_hmac('sha512', $msg, $binKey);
 echo $signature;

 // => a3efb70368bee502ea57a1a4708cac8912a5172075ea8dec2de2770dfbb4c8fb587f03fdadc0ca4f9e1bb024cfda12866295b259f5fb4df2fe14d960874a68ab

I don't understand why they pack the key and if I should do something similar with my key. I did the following in my Ruby code:

key = "FCEBA61A884A938E7E7FE4F5C68AA7F4A349768EE5957DDFBE99C1D05A09CBACF1FCF0A7084CB2E4CBA95193176C4395DE7F39EA9DBEBEF0907D77192AAE3E8A"
message = "param1=a&param2=b"

digest = OpenSSL::Digest.new('sha512')
signature = OpenSSL::HMAC.hexdigest(digest, key, message)

puts signature

# => d817611845246640d1224a0874bf60fed0956a367aa3069b7947cbec56903bb5d8c54df170f5504c586dad55e4f879c70cf1a40526cfc9f35411195822c535ed

回答1:


You need to do this in Ruby:

hash = OpenSSL::HMAC.hexdigest(digest, [key].pack('H*'), message)

The real issue here is that your PHP code uses two variable names for the message. You set $message, then use $msg, which means you're computing the hash for an undefined variable.




回答2:


The packing of the hex representation of the key back into a binary form is the bit you're missing.

See this post for example: https://blog.bigbinary.com/2011/07/20/ruby-pack-unpack.html

You'll want something like this:

signature = OpenSSL::HMAC.hexdigest(digest, key.pack('H'), message)



回答3:


I'm using this in my project:

bin_key = Array(keyTest).pack 'H*'
@hmac = OpenSSL::HMAC.hexdigest("SHA512", bin_key, msg).upcase

This works fine for me.



来源:https://stackoverflow.com/questions/48427354/ruby-hmac-signing-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!