Skip to content

Instantly share code, notes, and snippets.

@hectorups
Last active August 29, 2015 14:05
Show Gist options
  • Save hectorups/0561b7f184fba7c077a2 to your computer and use it in GitHub Desktop.
Save hectorups/0561b7f184fba7c077a2 to your computer and use it in GitHub Desktop.
Create S3 signature
#!/usr/bin/env ruby
require 'json'
require 'base64'
require 'openssl'
require 'digest/sha1'
aws_access_key = "AKIAJ7YGAAAGKXEVQX2Q"
aws_secret_key = "xxxxxx"
bucket_name = "bucket-name"
s3_directory = ''
# Build the Policy document that authorizes the upload and imposes limits
policy_document = %Q[
{"expiration": "2020-01-01T00:00:00Z",
"conditions": [
{"bucket": "#{bucket_name}"},
["starts-with", "$key", "#{s3_directory}"],
{"acl": "public-read"},
["starts-with", "$Content-Type", "image/jpeg"],
["content-length-range", 0, 10048576]
]
}
]
# Base64 encode the policy document
policy = Base64.encode64(policy_document).gsub("\n","")
signature = Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha1'), aws_secret_key, policy)).gsub("\n","")
# Output a curl example to upload to S3
command = %Q[curl -X POST -i \
-F "key=test2.jpeg" \
-F "acl=public-read" \
-F "AWSAccessKeyId=#{aws_access_key}" \
-F "Policy=#{policy}" \
-F "Signature=#{signature}" \
-F "Content-Type=image/jpeg" \
-F "[email protected]" \
http://#{bucket_name}.s3.amazonaws.com \n]
puts command
@hectorups
Copy link
Author

Script to create a signature to upload to S3. It also outputs a curl command example that can be used to check if everything works.

In my case I created a new aws user and give him permissions to only upload to the required S3 bucket.

Note: remember to update the signature before 2020 ...

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