Amazon
CloudFront签名URL与Amazon
S3签名URL的工作方式不同。CloudFront使用基于单独的CloudFront密钥对的RSA签名,您必须在Amazon Account
Credentials页面中对其进行设置。这是一些代码,可以使用M2Crypto库在Python中实际生成一个限时URL
:
为CloudFront创建密钥对
我认为唯一的方法就是通过亚马逊的网站。进入您的AWS“账户”页面,然后单击“安全凭证”链接。单击“密钥对”选项卡,然后单击“创建新的密钥对”。这将为您生成一个新的密钥对,并自动下载一个私钥文件(pk-
xxxxxxxxx.pem)。确保密钥文件安全和私密。还要记下亚马逊的“密钥对ID”,因为下一步将需要它。
在Python中生成一些URL
从boto 2.0版开始,似乎不支持生成签名的CloudFront
URL。Python在标准库中不包含RSA加密例程,因此我们将不得不使用其他库。在此示例中,我使用了M2Crypto。
对于非流媒体分发,您必须使用完整的Cloudfront
URL作为资源,但是对于流媒体,我们仅使用视频文件的对象名称。有关生成仅持续5分钟的URL的完整示例,请参见下面的代码。
此代码大致基于Amazon在CloudFront文档中提供的PHP示例代码。
from M2Crypto import EVPimport base64import timedef aws_url_base64_enpre(msg): msg_base64 = base64.b64enpre(msg) msg_base64 = msg_base64.replace('+', '-') msg_base64 = msg_base64.replace('=', '_') msg_base64 = msg_base64.replace('/', '~') return msg_base64def sign_string(message, priv_key_string): key = EVP.load_key_string(priv_key_string) key.reset_context(md='sha1') key.sign_init() key.sign_update(message) signature = key.sign_final() return signaturedef create_url(url, enpred_signature, key_pair_id, expires): signed_url = "%(url)s?Expires=%(expires)s&Signature=%(enpred_signature)s&Key-Pair-Id=%(key_pair_id)s" % { 'url':url, 'expires':expires, 'enpred_signature':enpred_signature, 'key_pair_id':key_pair_id, } return signed_urldef get_canned_policy_url(url, priv_key_string, key_pair_id, expires): #we manually construct this policy string to ensure formatting matches signature canned_policy = '{"Statement":[{"Resource":"%(url)s","Condition":{"DateLessThan":{"AWS:EpochTime":%(expires)s}}}]}' % {'url':url, 'expires':expires} #sign the non-enpred policy signature = sign_string(canned_policy, priv_key_string) #now base64 enpre the signature (URL safe as well) enpred_signature = aws_url_base64_enpre(signature) #combine these into a full url signed_url = create_url(url, enpred_signature, key_pair_id, expires); return signed_urldef enpre_query_param(resource): enc = resource enc = enc.replace('?', '%3F') enc = enc.replace('=', '%3D') enc = enc.replace('&', '%26') return enc#Set parameters for URLkey_pair_id = "APKAIAZVIO4BQ" #from the AWS accounts CloudFront tabpriv_key_file = "cloudfront-pk.pem" #your private keypair file# Use the FULL URL for non-streaming:resource = "http://34254534.cloudfront.net/video.mp4"#resource = 'video.mp4' #your resource (just object name for streaming videos)expires = int(time.time()) + 300 #5 min#Create the signed URLpriv_key_string = open(priv_key_file).read()signed_url = get_canned_policy_url(resource, priv_key_string, key_pair_id, expires)print(signed_url)#Flash player doesn't like query params so enpre them if you're using a streaming distribution#enc_url = enpre_query_param(signed_url)#print(enc_url)
确保您使用一个TrustedSigners参数设置您的分发,该参数设置为持有密钥对的帐户(如果是您自己的帐户,则为“ Self”)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)