Ruby way to generate a HMAC-SHA1 signature for OAuth
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)));"
Creating signature hmac-sha1 in rails for magento integration
Usually the base_string is the culprit. If you put the sample base string here, I can help you further
Creating Signature and Nonce for OAuth (Ruby)
For the signature:
def sign( key, base_string )
digest = OpenSSL::Digest::Digest.new( 'sha1' )
hmac = OpenSSL::HMAC.digest( digest, key, base_string )
Base64.encode64( hmac ).chomp.gsub( /\n/, '' )
end#def
You don't have to generate the nonce from the timestamp, but it can make sense since the timestamp is obviously unique, so it makes a good starting input for any randomisation function.
I use this, (that I got from another question on here and modified)
def nonce
rand(10 ** 30).to_s.rjust(30,'0')
end#def
but you can use anything that generates a unique string.
See this gist by erikeldridge on github and Beginner’s Guide to OAuth for more
Edit
I've since found there's a better way to generate random strings in the Ruby standard library, SecureRandom.
Related Topics
Ruby 'Pg' Gem Linking to Wrong Copy of Libpq.5.Dylib (On Osx)
Troubleshooting Ssl Certificates, Ruby, MAC Os X Yosemite
How to Log Every Method That's Called in a Ruby Program
Rake VS. Thor for Automation Scripts
How to Get the Number of Days in a Given Month in Ruby, Accounting for Year
Rails If Object.Nil? Then Magic '' in Views
How Much Performance Do You Get Out a Heroku Dynos/Workers
Installed Rails But the Rails Command Says It's Not Installed
Ruby: How to Define a Class Method in a Module
Ruby Use Array Tvalues to Index Nested Hash of Hash
How to Use Same Terminal Window After Using "Rails Server" Command
Message Queues in Ruby on Rails
How to Handle Constants in Ruby When Using Rails
Should I Define a Main Method in My Ruby Scripts
How to Dump an Http Request from Within Sinatra