Skip to content

Instantly share code, notes, and snippets.

@kplawver
Created June 21, 2010 21:52
Show Gist options
  • Save kplawver/447561 to your computer and use it in GitHub Desktop.
Save kplawver/447561 to your computer and use it in GitHub Desktop.
Simple example for streaming private content from CloudFront
require 'base64'
require 'openssl'
require 'sha1'
# This will generate URLs for streaming private content from CloudFront...
# I followed these instructions for setting up the bucket and CloudFront:
## http://support.rightscale.com/index.php?title=12-Guides/01-RightScale_Dashboard_User_Guide/02-Clouds/01-EC2/11-CloudFront/Serving_Private_Content
# I have a global config hash for my private key for S3:
# The access_key is the CloudFront key id you set up.
# The private key is the private key you get when you create the key pair.
# resource is the FULL CloudFront URL to the object you're trying to serve.
# I've gotten one successful test out of this so far, so your mileage may vary.
class CloudFront
include OpenSSL
include PKey
def self.generate_cloudfront_url(resource,time_unit=:hours,time_units=2)
o = self.sign(resource,time_unit,time_units)
"#{resource}?Expires=#{o[:expires]}&Signature=#{o[:signature]}&Key-Pair-Id=#{$S3_CONFIG['streaming']['access_key']}"
end
def self.sign(resource,time_unit=:hours,time_units=2)
expires = Time.now.advance(time_unit => time_units).to_i
request_string = "{\"Statement\":[{\"Resource\":\"#{resource}\",\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":#{expires}}}}]}"
signature = self.generate_signature(request_string)
{:expires => expires, :signature => signature}
end
def self.generate_signature(request_string)
private_key = RSA.new($S3_CONFIG['streaming']['private_key'])
signature = private_key.sign(OpenSSL::Digest::SHA1.new,request_string)
Base64.encode64(signature).gsub("\n","").gsub("+","-").gsub("=","_").gsub("/","~")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment