Skip to content

Instantly share code, notes, and snippets.

@J-L
Last active June 29, 2018 22:42
Show Gist options
  • Save J-L/bea5b454fd0a8e2eb2381d1540520aca to your computer and use it in GitHub Desktop.
Save J-L/bea5b454fd0a8e2eb2381d1540520aca to your computer and use it in GitHub Desktop.
Python SigV4 Auth for AWS- Simple
# Key derivation functions. See:
# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
def sign(key, msg):
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
def getSignatureKey(key, dateStamp, regionName, serviceName):
kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
kRegion = sign(kDate, regionName)
kService = sign(kRegion, serviceName)
kSigning = sign(kService, 'aws4_request')
return kSigning
def create_header(method, host, canonical_uri, access_key, secret_key, request_parameters, region, service ):
t = datetime.datetime.utcnow()
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
canonical_querystring = request_parameters
canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n'
signed_headers = 'host;x-amz-date'
payload_hash = hashlib.sha256('').hexdigest()
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request).hexdigest()
signing_key = getSignatureKey(secret_key, datestamp, region, service)
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
return {'x-amz-date':amzdate, 'Authorization':authorization_header}
#now call it
req = requests.get(url,headers= create_header(METHOD,HOST,canonical_uri,ACCESS_KEY,SECRET_KEY, "", REGION, SERVICE ))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment