Josh Peck - Nerdlog » Page 'Amazon FPS SigHelper for Ruby'

Amazon FPS SigHelper for Ruby

I spent a little more time hacking on Amazon FPS today. Ended up needing a signature helper that worked, and after a couple hours of messing with the one provided on the website, I ended up building my own.

The old one attempted to implement the raw RFC in the library itself. I opted out and used the openssl libraries. Sure, it doesn’t work on windows without some effort, but I don’t need it to.

require 'openssl' require 'base64' require 'uri' require 'cgi' # Provides a simpler signature helper than the one currently provided # by the community. # # Dependencies: # * OpenSSL # * Base64 # * URI # * CGI # # Usage: # SigHelper::get_encoded_url('http://example.com?a=1&b=2&c=3', 'AWS_SECRET_KEY') # module SigHelper def self.get_encoded_url(url, key) # Parse URL and set up vars uri = URI.parse(url) t = String.new q = CGI::parse(uri.query) # Sort and re-form sorted query string t = q.keys.sort.collect{|k| "#{k}=#{CGI::escape(q[k].shift)}" }.join('&') uri.query = t t = uri.path + '?' + uri.query # Generate signatures hmac = OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), key, t) sig = Base64.encode64(hmac) # URL-encode signature and return new url sig = CGI.escape(sig.strip) uri.query = uri.query + "&awsSignature=#{sig}" uri.to_s end end

Of course, this allows you to say something like this:

uri = URI::parse(SOME_URL) signed_url = SigHelper::get_encoded_url(uri.to_s, AWS_SECRET_ACCESS_KEY)
© 2008 Josh Peck - Nerdlog is powered by WordPress