Skip to content

Instantly share code, notes, and snippets.

@mcansky
Created August 23, 2012 08:59
Show Gist options
  • Save mcansky/3434417 to your computer and use it in GitHub Desktop.
Save mcansky/3434417 to your computer and use it in GitHub Desktop.
signing an aws s3 url
# 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
@zaus
Copy link

zaus commented Jul 17, 2014

multiple instances of '?' => '%3F' in encode_signs; do you also need !?

@OleMchls
Copy link

OleMchls commented Aug 9, 2014

@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

@lucasmartins
Copy link

"most up-to-date docs ever!"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment