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
Ruby Class Instance Variables and Inheritance
Routing Error - Uninitialized Constant
Adding a Submit Button Image to a Rails Form
Accepts_Nested_Attributes_For Rails 4 Is Not Deleting
How to Find Where a Ruby Method Is Declared
Using Soap and Other Standard Libraries in Ruby 1.9.2
Ruby: How to Generate CSV Files That Has Excel-Friendly Encoding
Ruby Split String by Repeating Characters or a Space
Learning Ruby: Recommended Blogs to Read
Rspec Testing Redirect to Url with Get Params
Rails - Displaying Foreign Key References in a Form
How to Make a Gemset in Rvm the Default
What Is the Best Diff Library in Ruby
Using Yield Inside Define_Method in Ruby
Access Node Attributes in Chef Library
How to Use Ajax Send Data to Controller in Ruby on Rails