# Python Version: 3.7
# 计算签名
# https://help.aliyun.com/document_detail/28761.html?spm=a2c4g.11186623.6.791.66725328JBIR5G
#https://sts.aliyuncs.com/?&AccessKeyId=testid&SignatureMethod=HMAC-SHA1&Version=2015-04-01&Action=AssumeRole&SignatureNonce=571f8fb8-506e-11e5-8e12-b8e8563dc8d2
params = {
"Action": "AssumeRole",
"Format": "JSON",
"Version": "2015-04-01",
"SignatureMethod": "HMAC-SHA1",
"SignatureNonce": "571f8fb8-506e-11e5-8e12-b8e8563dc8d2",
"SignatureVersion": "1.0",
"AccessKeyId": "testid",
"Timestamp": "2015-09-01T05:57:34Z",
"RoleArn": "acs:ram::1234567890123:role/firstrole",
"RoleSessionName": "client"
}
# 按照首字母排序
params_arr = list(params.items())
params_arr.sort(key=lambda x: x[0])
params_arr
from collections import OrderedDict
import urllib.parse
# 拼接 sign_str
sign_str = "GET&%2F&"
sign_dict = OrderedDict(params_arr)
params_str = urllib.parse.urlencode(sign_dict)
params_str = urllib.parse.quote(params_str)
sign_str += params_str
sign_str
# 验证签名用的 str 是否正确
eg = "GET&%2F&AccessKeyId%3Dtestid%26Action%3DAssumeRole%26Format%3DJSON%26RoleArn%3Dacs%253Aram%253A%253A1234567890123%253Arole%252Ffirstrole%26RoleSessionName%3Dclient%26SignatureMethod%3DHMAC-SHA1%26SignatureNonce%3D571f8fb8-506e-11e5-8e12-b8e8563dc8d2%26SignatureVersion%3D1.0%26Timestamp%3D2015-09-01T05%253A57%253A34Z%26Version%3D2015-04-01"
assert sign_str == eg
import hashlib
import hmac
import base64
h = hmac.new('testsecret&'.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha1)
sign = h.digest()
sign = base64.b64encode(sign).decode()
sign
# 验证签名值
assert sign == 'gNI7b0AyKZHxDgjBGPDgJ1Ce3L4='