Ruby way to generate a HMAC-SHA1 signature for OAuth

Roberto picture Roberto · Nov 3, 2010 · Viewed 27.2k times · Source

I'm writing a small ruby program to play with Twitter over OAuth and have yet to find a right way to do the HMAC-SHA1 signature. So far, I messed around with

Base64.encode64(OpenSSL::HMAC.hexdigest(digest, key, stuff)).chomp

But this outputs something that Twitter rejects, not being a valid signature. I actually solved it in the worse way possible, please try not to slap me:

php -r "echo rawurlencode(base64_encode(hash_hmac('sha1', '#{@signature}', '#{llave}', true)));"

This last one actually works and I can go around doing my stuff.

I'd like some tips on how to do actually do this without reverting back to PHP. I'm not much of a fan of libraries while I'm trying to learn a language, so gems are pretty much out of the question.

Thanks!

Answer

Ronen Botzer picture Ronen Botzer · Jan 24, 2011

The following is equivalent to your PHP code, though I chose not to wrap it in a single line.

I'm using the gem ruby-hmac, because it works with 1.8 as well as Ruby 1.9. If you're exclusively using Ruby 1.9 I believe the standard library package 'digest' has HMAC implemented (but this is missing in the 1.8 version of the package). Make sure to gem install ruby-hmac

require 'rubygems'
require 'base64'
require 'cgi'
require 'hmac-sha1'

key = '1234'
signature = 'abcdef'
hmac = HMAC::SHA1.new(key)
hmac.update(signature)
puts CGI.escape(Base64.encode64("#{hmac.digest}\n"))

# equivalent to:
# php -r "echo rawurlencode(base64_encode(hash_hmac('sha1', 'abcdef', '1234', true)));"

Better yet, use the standard library package OpenSSL (which most Linux and MacOS have out of the box). This code will work on Ruby 1.8 and 1.9:

require 'base64'
require 'cgi'
require 'openssl'

key = '1234'
signature = 'abcdef'
puts CGI.escape(Base64.encode64("#{OpenSSL::HMAC.digest('sha1',key, signature)}\n"))

# equivalent to:
# php -r "echo rawurlencode(base64_encode(hash_hmac('sha1', 'abcdef', '1234', true)));"