欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python3生成腾讯云cos的签名sign

程序员文章站 2022-07-03 12:49:30
...

这两天在折腾有关腾讯云的对象存储COS功能,之前用java语言写过,下载了相关的SDK,这次开发语言变为了python,遇到从bucket桶中下载私有读写文件的签名问题,一般的文件下载链接格式如下:
https://桶名-APP_ID.cos.所属区.myqcloud.com/test.txt?sign=XXXX
前面路径好说,关键是生成签名问题,下面便是用python生成签名的代码:

#!/usr/local/bin/python3
# coding=utf-8

import time
import random
import hmac
import hashlib
import base64

SecretId = 'XXXXXXXXXXXXXXXXXXX'
SecretKey = 'XXXXXXXXXXXXXXXXX'
Bucket = 'XXXXXX'
AppId = '125xxxxx06'
TimeStamp = int(time.time())
ExpireTime = TimeStamp + 86400 * 90
Random = random.randint(0, 100000)
Original = "a="+AppId+"&b="+Bucket+"&k="+SecretId+"&e="+str(ExpireTime)+"&t="+str(TimeStamp)+"&r="+str(Random)+"&f="

Hmac = hmac.new(bytes(SecretKey, 'utf-8'), bytes(Original, 'utf-8'), hashlib.sha1)
Sha1 = Hmac.digest()
Signature = bytes(Sha1) + bytes(Original, 'utf-8')
Signature2 = base64.b64encode(Signature)
-- 最后生成的sign如下
sign = str(Signature2, 'UTF-8')
print("Original: ", Original)
print("HMAC-SHA1: ", Sha1)
print("Signature before BASE64: ", Signature)
print("Signature after BASE64: ", sign)

以上希望对大家有用~

生成逻辑及签名工具请参考官方文档:

签名工具

签名算法