signCookie.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. from boto.cloudfront.distribution import Distribution
  2. from cryptography.hazmat.primitives.asymmetric import padding
  3. from cryptography.hazmat.primitives import serialization
  4. from cryptography.hazmat.backends import default_backend
  5. from cryptography.hazmat.primitives import hashes
  6. import base64
  7. import datetime
  8. from var_dump import var_dump
  9. import time
  10. class BetterThanBoto(Distribution):
  11. def sign_rsa(self, message):
  12. private_key = serialization.load_pem_private_key(self.keyfile, password=None,
  13. backend=default_backend())
  14. signer = private_key.signer(padding.PKCS1v15(), hashes.SHA1())
  15. message = message.encode('utf-8')
  16. signer.update(message)
  17. return signer.finalize()
  18. def _sign_string(self, message, private_key_file=None, private_key_string=None):
  19. if private_key_file:
  20. self.keyfile = open(private_key_file, 'rb').read()
  21. elif private_key_string:
  22. self.keyfile = private_key_string.encode('utf-8')
  23. return self.sign_rsa(message)
  24. @staticmethod
  25. def _url_base64_encode(msg):
  26. """
  27. Base64 encodes a string using the URL-safe characters specified by
  28. Amazon.
  29. """
  30. msg_base64 = base64.b64encode(msg).decode('utf-8')
  31. msg_base64 = msg_base64.replace('+', '-')
  32. msg_base64 = msg_base64.replace('=', '_')
  33. msg_base64 = msg_base64.replace('/', '~')
  34. return msg_base64
  35. def generate_signature(self, policy, private_key_file=None):
  36. """
  37. :param policy: no-whitespace json str (NOT encoded yet)
  38. :param private_key_file: your .pem file with which to sign the policy
  39. :return: encoded signature for use in cookie
  40. """
  41. # Distribution._create_signing_params()
  42. signature = self._sign_string(policy, private_key_file)
  43. # now base64 encode the signature & make URL safe
  44. encoded_signature = self._url_base64_encode(signature)
  45. return encoded_signature
  46. def create_signed_cookies(self, url, private_key_file=None, keypair_id=None,
  47. expires_at=20, secure=True):
  48. policy = self._custom_policy(
  49. url,
  50. expires_at
  51. )
  52. encoded_policy = self._url_base64_encode(policy.encode('utf-8'))
  53. signature = self.generate_signature(
  54. policy, private_key_file=private_key_file
  55. )
  56. cookies = {
  57. "CloudFront-Policy": encoded_policy,
  58. "CloudFront-Signature": signature,
  59. "CloudFront-Key-Pair-Id": keypair_id
  60. }
  61. return cookies
  62. def sign_to_cloudfront(object_url, expires_at):
  63. """ Sign URL to distribute file"""
  64. cf = BetterThanBoto()
  65. url = cf.create_signed_url(url=object_url,
  66. keypair_id="APKAINI6BNPKV54NHH7Q",
  67. expire_time=expires_at,
  68. private_key_file="D:/project_svn/Ansjer/test/pk-APKAINI6BNPKV54NHH7Q.pem")
  69. return url
  70. def create_signed_cookies(object_url, expires_at):
  71. """
  72. Create a signed cookie
  73. """
  74. cf = BetterThanBoto()
  75. cookies = cf.create_signed_cookies(url=object_url, keypair_id="APKAINI6BNPKV54NHH7Q", expires_at=expires_at,
  76. private_key_file="D:/project_svn/Ansjer/test/pk-APKAINI6BNPKV54NHH7Q.pem")
  77. return cookies
  78. expire_date = int(time.time()) + 7200
  79. object_url = 'http://d3596w5a6euckc.cloudfront.net/vod/2N1K3LE78TYJ38CE111A_99/1527152855.m3u8'
  80. # object_url = 'http://d3596w5a6euckc.cloudfront.net/vod/2N1K3LE78TYJ38CE111A_99/*'
  81. # cookie_data = create_signed_cookies(object_url, expire_date)
  82. # print(cookie_data)
  83. # exit()
  84. cookie_data = {'CloudFront-Policy': 'eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cDovL2QzNTk2dzVhNmV1Y2tjLmNsb3VkZnJvbnQubmV0L3ZvZC8yTjFLM0xFNzhUWUozOENFMTExQV85OS8qIiwiQ29uZGl0aW9uIjp7IkRhdGVMZXNzVGhhbiI6eyJBV1M6RXBvY2hUaW1lIjoxNTI3NTA1MDA1fX19XX0_', 'CloudFront-Signature': 'IQYo7PdwXLRyEywSon6HBvuaEOLqTGH6qWAx1Fk3HrSK6N325f0oXcvpZ1eSVUv353YUrd6bKPDE9tLEOPuIitILNQt5tP593C5OIX4jc15RpUpTuEQdlVlO7~SfnxtHXIqukD20GXWIfCagneNj1~F2OD5Tn8ER2stJY1IK~v12VPXAA-cWqoKc6WyVZfzJs0SkJIfQDeDtSOkKD0fP8TOBM2i4XQzbcl9NviNrueG-bZwrCondlw6K5g4TOVS41QQplEIOwb1AzxBb8QvDXxaQ-Kcmy5ME-vpfdBqdHrgreAGZIliZyLWA3qIJ71w67YIzsnCvCMytULDE7w-d4Q__', 'CloudFront-Key-Pair-Id': 'APKAINI6BNPKV54NHH7Q'}
  85. print(cookie_data)
  86. import requests
  87. cookies = cookie_data
  88. headers = {}
  89. # exit()
  90. s = requests.Session()
  91. res = s.get(object_url, headers=headers, cookies=cookies)
  92. print(res.text)