A signer to create a signed CloudFront URL. First you create a cloudfront signer based on a normalized RSA signer:: import rsa def rsa_signer(message): private_key = open('private_key.pem', 'r').read() return rsa.sign( message,
| 356 | |
| 357 | |
| 358 | class CloudFrontSigner: |
| 359 | '''A signer to create a signed CloudFront URL. |
| 360 | |
| 361 | First you create a cloudfront signer based on a normalized RSA signer:: |
| 362 | |
| 363 | import rsa |
| 364 | def rsa_signer(message): |
| 365 | private_key = open('private_key.pem', 'r').read() |
| 366 | return rsa.sign( |
| 367 | message, |
| 368 | rsa.PrivateKey.load_pkcs1(private_key.encode('utf8')), |
| 369 | 'SHA-1') # CloudFront requires SHA-1 hash |
| 370 | cf_signer = CloudFrontSigner(key_id, rsa_signer) |
| 371 | |
| 372 | To sign with a canned policy:: |
| 373 | |
| 374 | signed_url = cf_signer.generate_signed_url( |
| 375 | url, date_less_than=datetime(2015, 12, 1)) |
| 376 | |
| 377 | To sign with a custom policy:: |
| 378 | |
| 379 | signed_url = cf_signer.generate_signed_url(url, policy=my_policy) |
| 380 | ''' |
| 381 | |
| 382 | def __init__(self, key_id, rsa_signer): |
| 383 | """Create a CloudFrontSigner. |
| 384 | |
| 385 | :type key_id: str |
| 386 | :param key_id: The CloudFront Key Pair ID |
| 387 | |
| 388 | :type rsa_signer: callable |
| 389 | :param rsa_signer: An RSA signer. |
| 390 | Its only input parameter will be the message to be signed, |
| 391 | and its output will be the signed content as a binary string. |
| 392 | The hash algorithm needed by CloudFront is SHA-1. |
| 393 | """ |
| 394 | self.key_id = key_id |
| 395 | self.rsa_signer = rsa_signer |
| 396 | |
| 397 | def generate_presigned_url(self, url, date_less_than=None, policy=None): |
| 398 | """Creates a signed CloudFront URL based on given parameters. |
| 399 | |
| 400 | :type url: str |
| 401 | :param url: The URL of the protected object |
| 402 | |
| 403 | :type date_less_than: datetime |
| 404 | :param date_less_than: The URL will expire after that date and time |
| 405 | |
| 406 | :type policy: str |
| 407 | :param policy: The custom policy, possibly built by self.build_policy() |
| 408 | |
| 409 | :rtype: str |
| 410 | :return: The signed URL. |
| 411 | """ |
| 412 | if ( |
| 413 | date_less_than is not None |
| 414 | and policy is not None |
| 415 | or date_less_than is None |