Using Hmac Sha256 in Ruby

Using HMAC SHA256 in Ruby

According to the documentation OpenSSL::HMAC.digest

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

If you have a problem using that maybe you need a hex encoded form provided by 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"

Convert C# to Ruby - HMAC SHA256 function

Finally got the monkey of my back!

I don't really need to create a sha256 digest object after all, I just had to put the 'sha256' parameter.

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)

thanks to this link

Ruby hmac sha256 hash differs for variable versus literal

looks like Base64.encode64 appends a "\n" to the end of its output so

from docs

encode64(bin) Returns the Base64-encoded
version of bin. This method complies with RFC 2045. Line feeds are
added to every 60 encoded characters.

this

contentmd5 = Base64.encode64(OpenSSL::Digest::MD5.digest(content))

returns

"XUFAKrxLKna5cZ2REBfFkg==\n"

not

 "XUFAKrxLKna5cZ2REBfFkg=="

--

you can use strict_encode64 to not include line feeds so:

contentmd5 = Base64.strict_encode64(OpenSSL::Digest::MD5.digest(content))

returns

 => "XUFAKrxLKna5cZ2REBfFkg=="


Related Topics



Leave a reply



Submit