Dec 1, 2012

Create a URL Signature for Amazon CloudFront Using Python

There is no official document to create a url signature for Amazon CloudFront in Python. I found an easy way to do it.

from tlslite.utils import keyfactory
from base64 import b64encode
import time

url = "http://d3iwlid5dsmdb3.cloudfront.net/_default_san.png"
expires = int(time.time() + 60)
privkey_file = "pk-APKAJ4YNPASFVCNBXK3A-cloudfront.pem"
key_pair_id = "APKAJ4YNPASFVCNBXK3A"

policy = '{"Statement":[{"Resource":"%s","Condition":{"DateLessThan":{"AWS:EpochTime":%d}}}]}' % (url, expires)
privkey = keyfactory.parsePrivateKey(open(privkey_file).read())            
print '%s?Expires=%d&Signature=%s&Key-Pair-Id=%s' % (url, expires, b64encode(privkey.hashAndSign(policy)), key_pair_id)

The library tlslite is very easy to use. boto also has a method to create signed url but it uses M2Crypto. To install M2Crypto, swig command is required but my OSX does not have it. If you do not like to install swig, tlslite is a good option.

No comments: