以下是使用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 = '