cos_auth.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import random
  4. import time
  5. import urllib
  6. import hmac
  7. import hashlib
  8. import binascii
  9. import base64
  10. class Auth(object):
  11. def __init__(self, cred):
  12. self.cred = cred
  13. def app_sign(self, bucket, cos_path, expired, upload_sign=True):
  14. appid = self.cred.get_appid()
  15. bucket = bucket.encode('utf8')
  16. secret_id = self.cred.get_secret_id().encode('utf8')
  17. now = int(time.time())
  18. rdm = random.randint(0, 999999999)
  19. cos_path = urllib.quote(cos_path.encode('utf8'), '~/')
  20. if upload_sign:
  21. fileid = '/%s/%s%s' % (appid, bucket, cos_path)
  22. else:
  23. fileid = cos_path
  24. if expired != 0 and expired < now:
  25. expired = now + expired
  26. sign_tuple = (appid, secret_id, expired, now, rdm, fileid, bucket)
  27. plain_text = 'a=%s&k=%s&e=%d&t=%d&r=%d&f=%s&b=%s' % sign_tuple
  28. secret_key = self.cred.get_secret_key().encode('utf8')
  29. sha1_hmac = hmac.new(secret_key, plain_text, hashlib.sha1)
  30. hmac_digest = sha1_hmac.hexdigest()
  31. hmac_digest = binascii.unhexlify(hmac_digest)
  32. sign_hex = hmac_digest + plain_text
  33. sign_base64 = base64.b64encode(sign_hex)
  34. return sign_base64
  35. def sign_once(self, bucket, cos_path):
  36. """单次签名(针对删除和更新操作)
  37. :param bucket: bucket名称
  38. :param cos_path: 要操作的cos路径, 以'/'开始
  39. :return: 签名字符串
  40. """
  41. return self.app_sign(bucket, cos_path, 0)
  42. def sign_more(self, bucket, cos_path, expired):
  43. """多次签名(针对上传文件,创建目录, 获取文件目录属性, 拉取目录列表)
  44. :param bucket: bucket名称
  45. :param cos_path: 要操作的cos路径, 以'/'开始
  46. :param expired: 签名过期时间, UNIX时间戳, 如想让签名在30秒后过期, 即可将expired设成当前时间加上30秒
  47. :return: 签名字符串
  48. """
  49. return self.app_sign(bucket, cos_path, expired)
  50. def sign_download(self, bucket, cos_path, expired):
  51. """下载签名(用于获取后拼接成下载链接,下载私有bucket的文件)
  52. :param bucket: bucket名称
  53. :param cos_path: 要下载的cos文件路径, 以'/'开始
  54. :param expired: 签名过期时间, UNIX时间戳, 如想让签名在30秒后过期, 即可将expired设成当前时间加上30秒
  55. :return: 签名字符串
  56. """
  57. return self.app_sign(bucket, cos_path, expired, False)