Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@rkh

This comment has been minimized.

Copy link

@rkh rkh commented Sep 11, 2013

URI.escape takes a regexp as second parameter to match the characters to escape

@zaus

This comment has been minimized.

Copy link

@zaus zaus commented Jul 17, 2014

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

@OleMchls

This comment has been minimized.

Copy link

@OleMchls 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

This comment has been minimized.

Copy link

@lucasmartins lucasmartins commented Oct 30, 2014

"most up-to-date docs ever!"

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