Using HMAC SHA256 in Ruby

I am trying to apply HMAC-SHA256 to generate a key for the Rest API.

I am doing something like this:

def generateTransactionHash(stringToHash)
  key = '123'
  data = 'stringToHash'
  digest = OpenSSL::Digest.new('sha256')

  hmac = OpenSSL::HMAC.digest(digest, key, data)
  puts hmac
end

The result of this is always this: (if I put "12345" as a parameter or "HUSYED815X", I get the same)

ۯw/{o   p T    :  a h  E|q

The API is not working because of this ... Can someone help me with this?

+11
source share
3 answers

According to the documentation OpenSSL::HMAC.digest

Returns the authentication code that the instance represents as a binary string.

If you are having problems using this, you may need the hexadecimal form provided OpenSSL::HMAC.hexdigest

Example

key = 'key'
data = 'The quick brown fox jumps over the lazy dog'
digest = OpenSSL::Digest.new('sha256')

OpenSSL::HMAC.digest(digest, key, data)
#=> "\xF7\xBC\x83\xF40S\x84$\xB12\x98\xE6\xAAo\xB1C\xEFMY\xA1IF\x17Y\x97G\x9D\xBC-\x1A<\xD8"

OpenSSL::HMAC.hexdigest(digest, key, data)
#=> "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"
+15
source

Try the following:

hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), key, data)
+11

(Ticketmatic) HMAC, , HMAC .

hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret_key, access_key + name + time)
req = Net::HTTP::Get.new(uri)
req['Authorization'] = "TM-HMAC-SHA256 key=#{access_key} ts=#{time} sign=#{hmac}"
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }

You can find the full point here.

And a blog with a more detailed explanation here

0
source

Source: https://habr.com/ru/post/1624787/


All Articles