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
def hmac_sha1(data, secret=HOST_KEY)
require 'base64'
require 'cgi'
require 'openssl'
hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha1'), secret.encode("ASCII"), data.encode("ASCII"))
return hmac
end
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)));"