Skip to content

Instantly share code, notes, and snippets.

@jsomara
Created August 18, 2016 22:01
Show Gist options
  • Save jsomara/037ddc0127cc72948f1ee62d2819e5a5 to your computer and use it in GitHub Desktop.
Save jsomara/037ddc0127cc72948f1ee62d2819e5a5 to your computer and use it in GitHub Desktop.
S3 Signature Request Process v4, in ruby/rails
# Algorithm: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-authentication-HTTPPOST.html
# policy_params are the input policy as a rails request param object, which expects :conditions & :expiration
class S3Signer
def self.get_signature_key(key, date_stamp, region_name, service_name)
k_date = OpenSSL::HMAC.digest('sha256', "AWS4" + key, date_stamp)
k_region = OpenSSL::HMAC.digest('sha256', k_date, region_name)
k_service = OpenSSL::HMAC.digest('sha256', k_region, service_name)
k_signing = OpenSSL::HMAC.digest('sha256', k_service, "aws4_request")
k_signing
end
def self.sign_policy(policy_params, host)
conditions = policy_params[:conditions]
condz = {}
conditions.each do |c|
if c.respond_to? 'keys'
condz[c.keys[0]] = c[c.keys[0]]
end
end
policy = Base64.encode64(policy_params.to_json.encode('UTF-8')).gsub("\n","")
amzdate = condz['x-amz-date']
secret_key = ENV['AWS_SECRET_ACCESS_KEY']
datestamp = amzdate.split('T')[0]
region = 'us-west-2'
service = 's3'
signing_key = get_signature_key(secret_key, datestamp, region, service)
signature = OpenSSL::HMAC.hexdigest('sha256', signing_key, policy)
return { policy: policy, signature: signature }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment