AWSElastic'GET'API请求使用URL--Python3.8||AuthAWSSignature改为中文
创始人
2024-09-25 07:02:12
0

以下是使用Python 3.8和AWS签名身份验证对AWS Elastic的GET API请求进行URL编码的示例代码:

import requests
import datetime
import hashlib
import hmac
import urllib.parse

# AWS Key
ACCESS_KEY = 'YOUR_ACCESS_KEY'
SECRET_KEY = 'YOUR_SECRET_KEY'

# Parameter values for the request
method = 'GET'
service = 'ec2'
host = 'ec2.amazonaws.com'
region = 'us-east-1'
endpoint = 'https://ec2.amazonaws.com'

# Define the request parameters
params = {'Action': 'DescribeRegions',
          'Version': '2013-10-15'}

# Define the date and time variable
t = datetime.datetime.utcnow()
amz_date = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d')

# Create the canonical query string
canonical_querystring = ''
for param in sorted(params.items()):
    canonical_querystring += urllib.parse.quote(param[0], safe='') + '=' + urllib.parse.quote(param[1], safe='') + '&'

# Create the canonical headers and signed headers
canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'
signed_headers = 'host;x-amz-date'
payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()

# Create the canonical request and hash it
canonical_request = method + '\n' + '/' + '\n' + canonical_querystring[:-1] + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
hashed_canonical_request = hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()

# Create the string to sign
string_to_sign = 'AWS4-HMAC-SHA256' + '\n' + amz_date + '\n' + datestamp + '/' + region + '/' + service + '/' + 'aws4_request' + '\n' + hashed_canonical_request

# Create the signing key with the crucial date
kDate = hmac.new(('AWS4' + SECRET_KEY).encode('utf-8'), datestamp.encode('utf-8'), hashlib.sha256).digest()
kRegion = hmac.new(kDate, region.encode('utf-8'), hashlib.sha256).digest()
kService = hmac.new(kRegion, service.encode('utf-8'), hashlib.sha256).digest()
kSigning = hmac.new(kService, b'aws4_request', hashlib.sha256).digest()

# Create the signature
signature = hmac.new(kSigning, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest()

# Create the authorization header
authorization_header = '

相关内容

热门资讯

安卓换鸿蒙系统会卡吗,体验流畅... 最近手机圈可是热闹非凡呢!不少安卓用户都在议论纷纷,说鸿蒙系统要来啦!那么,安卓手机换上鸿蒙系统后,...
app安卓系统登录不了,解锁登... 最近是不是你也遇到了这样的烦恼:手机里那个心爱的APP,突然就登录不上了?别急,让我来帮你一步步排查...
安卓系统拦截短信在哪,安卓系统... 你是不是也遇到了这种情况:手机里突然冒出了很多垃圾短信,烦不胜烦?别急,今天就来教你怎么在安卓系统里...
安卓系统要维护多久,安卓系统维... 你有没有想过,你的安卓手机里那个陪伴你度过了无数日夜的安卓系统,它究竟要陪伴你多久呢?这个问题,估计...
windows官网系统多少钱 Windows官网系统价格一览:了解正版Windows的购买成本Windows 11官方价格解析微软...
安卓系统如何卸载app,轻松掌... 手机里的App越来越多,是不是感觉内存不够用了?别急,今天就来教你怎么轻松卸载安卓系统里的App,让...
怎么复制照片安卓系统,操作步骤... 亲爱的手机控们,是不是有时候想把自己的手机照片分享给朋友,或者备份到电脑上呢?别急,今天就来教你怎么...
安卓系统应用怎么重装,安卓应用... 手机里的安卓应用突然罢工了,是不是让你头疼不已?别急,今天就来手把手教你如何重装安卓系统应用,让你的...
iwatch怎么连接安卓系统,... 你有没有想过,那款时尚又实用的iWatch,竟然只能和iPhone好上好?别急,今天就来给你揭秘,怎...
iphone系统与安卓系统更新... 最近是不是你也遇到了这样的烦恼?手机更新系统总是失败,急得你团团转。别急,今天就来给你揭秘为什么iP...