1,腾讯云api的签名生成及使用

腾讯云API途径:
1,通过API文档
2,通过SDK
3,通过CLI

签名流程:
1,申请安全凭证
2,生成签名串
2-1,参数排序
2-2,拼接请求字符串
2-3,拼接签名与原文字符串
2-4,生成签名串
3,签名串编码

1,申请安全凭证
登陆到api密钥控制台,创建SecretId/SecretKey
2,生成签名串
2-1,参数排序
首先对所有请求参数按参数名做字典序升序排列,所谓字典序升序排列,直观上就
如同在字典中排列单词一样排序,按照字母表或数字表里递增顺序的排列次序,即先
考虑第一个字母,在相同的情况下考虑第二个字母,依次类推。
{
'a':1,
'b':2
}
2-2,拼接请求字符串
将上面排序好的请求参数格式化成"参数名称"="参数值"的形式,参数值为原始值
而非url编码后的值。然后将格式化后的各个参数用&拼接在一起,最终生成的请求字符串为:
a=1&b=2&f=E

2-3,拼接签名与原文字符串
接下来拼接签名与原文字符串,由以下几个参数构成,
2-3-1,请求方法
2-3-2,请求主机,即接口请求域名: cvm.tencentcloudapi.com
2-3-3,请求路径
2-3-4,请求字符串,即上面生成的请求字符串

签名原文字符串的拼接规则为:请求方法+请求主机+请求路径+?+请求字符串

2-4-4,生成签名串
生成签名串可以理解为2个步骤
1)首先使用HMAC-SHA1算法加密
2)然后将生成的签名串使用Base64进行编码,即获得最终的签名串

3,签名串编码
生成的签名串并不能直接作为请求参数,需要对其进行URL编码。
注意:如果用户的请求方法是GET,则对所有请求参数值均需要做URL编码。

#! /usr/bin/python3
# -*- coding:utf-8 -*-

SecretId='AKID79vAsfgdfgdfhdrturt9R4092SmrtyiyRhHDeRpxcA5apcIK3AWc'
SecretKey='ziDgvpV9WegT071dtghdfgfjf5ykjyFuQvFhfhjhjfhjfNE1Zwxvrgq'

import time
uri = 'cvm.tencentcloudapi.com'

paramDict = {
    'Action':'DescribeRegions',
    'Version':'2017-03-12',
    'SecretId':SecretId,
    'Nonce':123456,
    'Timestamp':int(time.time()),
}

tempList = []
tempDict = {}

for eveKey,eveValue in paramDict.items():
    tempLowerData =eveKey.lower()
    tempList.append(tempLowerData)
    tempDict[tempLowerData] = eveKey
tempList.sort()
print(tempDict)
print(tempList)

resultList = []
for eveData in tempList:
    tempStr = str(tempDict[eveData]) + '=' + str(paramDict[tempDict[eveData]])
    resultList.append(tempStr)
print(resultList)

sourceStr = '&'.join(resultList)
print(sourceStr)

requestStr = '%s%s%s%s%s' %('GET',uri,'/','?',sourceStr)

print(requestStr)

import sys
if sys.version_info[0] > 2:
    signStr = requestStr.encode('utf-8')
    print(signStr)
    SecretKey = SecretKey.encode('utf-8')

import hashlib
digestmod = hashlib.sha1

import hmac
hashed = hmac.new(SecretKey,signStr,digestmod)

import binascii
base64Data = binascii.b2a_base64(hashed.digest())[:-1]
print(type(base64Data))

if sys.version_info[0] > 2:
    base64Data.decode()

import urllib.parse
base64Data = urllib.parse.quote(base64Data)
url = "https://" + uri + '/' + '?' + sourceStr + '&Signature=' + base64Data
print(url)

import urllib.request
import json

#print(urllib.request.urlopen(url).read().decode('utf-8'))
for eveData in json.loads(urllib.request.urlopen(url).read().decode('utf-8'))['Response']['RegionSet']:
    print(eveData)

猜你喜欢

转载自www.cnblogs.com/k8s-pod/p/12904585.html
今日推荐