Ruby Way to Generate a Hmac-Sha1 Signature for Oauth

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



Leave a reply



Submit