Created
August 23, 2012 08:59
-
-
Save mcansky/3434417 to your computer and use it in GitHub Desktop.
signing an aws s3 url
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding : utf-8 | |
require 'openssl' | |
require 'digest/sha1' | |
require 'base64' | |
module Aws | |
extend self | |
def signed_url(path, expire_date) | |
digest = OpenSSL::Digest::Digest.new('sha1') | |
can_string = "GET\n\n\n#{expire_date}\n/#{S3_BUCKET}/#{path}" | |
hmac = OpenSSL::HMAC.digest(digest, S3_SECRET_ACCESS_KEY, can_string) | |
signature = URI.escape(Base64.encode64(hmac).strip).encode_signs | |
"https://s3.amazonaws.com/#{S3_BUCKET}/#{path}?AWSAccessKeyId=#{S3_ACCESS_KEY_ID}&Expires=#{expire_date}&Signature=#{signature}" | |
end | |
end | |
class String | |
def encode_signs | |
signs = {'+' => "%2B", '=' => "%3D", '?' => '%3F', '@' => '%40', | |
'$' => '%24', '&' => '%26', ',' => '%2C', '/' => '%2F', ':' => '%3A', | |
';' => '%3B', '?' => '%3F'} | |
signs.keys.each do |key| | |
self.gsub!(key, signs[key]) | |
end | |
self | |
end | |
end |
multiple instances of '?' => '%3F'
in encode_signs
; do you also need !
?
@ALL please note that this is part of the official 'aws-sdk' already http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/S3Object.html#url_for-instance_method
"most up-to-date docs ever!"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
URI.escape
takes a regexp as second parameter to match the characters to escape