· 7 years ago · Feb 08, 2018, 03:58 PM
1# TERMCAT Version 4 signing example
2
3# EC2 API (DescribeRegions)
4
5# See: http://docs.termcat.amazon.com/general/latest/gr/sigv4_signing.html
6# This version makes a GET request and passes the signature
7# in the Authorization header.
8import sys, os, base64, datetime, hashlib, hmac
9import requests # pip install requests
10import time
11
12# ************* REQUEST VALUES *************
13method = 'GET'
14service = 'terms'
15host = 'api.termcat.cat'
16region = 'eu-cat-1'
17endpoint = 'https://api.termcat.cat/v1.0/cerca/cercaterm'
18request_parameters = 'condicio=match&query=tomaquera'
19
20# Key derivation functions. See:
21# http://docs.termcat.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
22def sign(key, msg):
23 return hmac.new(key, msg.encode('utf-8'), hashlib.sha512).digest()
24
25def getSignatureKey(key, dateStamp, regionName, serviceName):
26 kDate = sign(('TERMCAT4' + key).encode('utf-8'), dateStamp)
27 kRegion = sign(kDate, regionName)
28 kService = sign(kRegion, serviceName)
29 kSigning = sign(kService, 'termcat4_request')
30 return kSigning
31
32# Read TERMCAT access key from env. variables or configuration file. Best practice is NOT
33# to embed credentials in code.
34access_key = 'AKC627UID87363KOQAOZ'
35secret_key = 'IvttA[c1r,=IGcjNcw|]9Mj]tm*[,_-N>v%Gd^]k'
36if access_key is None or secret_key is None:
37 print('No access key is available.')
38 sys.exit()
39
40# Create a date for headers and the credential string
41t = datetime.datetime.utcnow()
42termcatdate = t.strftime('%Y%m%dT%H%M%SZ')
43datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope
44
45
46# ************* TASK 1: CREATE A CANONICAL REQUEST *************
47# http://docs.termcat.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
48
49# Step 1 is to define the verb (GET, POST, etc.)--already done.
50
51# Step 2: Create canonical URI--the part of the URI from domain to query
52# string (use '/' if no path)
53#canonical_uri = '/'
54canonical_uri = '/v1.0/cerca/cercaterm'
55
56
57# Step 3: Create the canonical query string. In this example (a GET request),
58# request parameters are in the query string. Query string values must
59# be URL-encoded (space=%20). The parameters must be sorted by name.
60# For this example, the query string is pre-formatted in the request_parameters variable.
61canonical_querystring = request_parameters
62
63# Step 4: Create the canonical headers and signed headers. Header names
64# must be trimmed and lowercase, and sorted in code point order from
65# low to high. Note that there is a trailing \n.
66#canonical_headers = 'host:' + host + '\n' + 'x-termcat-date:' + termcatdate + '\n'
67canonical_headers = 'content-type:application/x-www-form-urlencoded; charset=utf-8' + '\n' + 'host:' + host + '\n' + 'x-termcat-content-sha512:' + hashlib.sha512('').hexdigest() + '\n' + 'x-termcat-date:' + termcatdate + '\n'
68
69# Step 5: Create the list of signed headers. This lists the headers
70# in the canonical_headers list, delimited with ";" and in alpha order.
71# Note: The request can include any headers; canonical_headers and
72# signed_headers lists those that you want to be included in the
73# hash of the request. "Host" and "x-termcat-date" are always required.
74#signed_headers = 'host;x-termcat-date'
75signed_headers = 'content-type;host;x-termcat-content-sha512;x-termcat-date'
76
77# Step 6: Create payload hash (hash of the request body content). For GET
78# requests, the payload is an empty string ("").
79payload_hash = hashlib.sha512('').hexdigest()
80
81# Step 7: Combine elements to create create canonical request
82canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
83
84
85# ************* TASK 2: CREATE THE STRING TO SIGN*************
86# Match the algorithm to the hashing algorithm you use, either SHA-1 or
87# SHA-256 (recommended)
88algorithm = 'TERMCAT4-HMAC-SHA512'
89credential_scope = datestamp + '/' + region + '/' + service + '/' + 'termcat4_request'
90string_to_sign = algorithm + '\n' + termcatdate + '\n' + credential_scope + '\n' + hashlib.sha512(canonical_request).hexdigest()
91
92
93# ************* TASK 3: CALCULATE THE SIGNATURE *************
94# Create the signing key using the function defined above.
95signing_key = getSignatureKey(secret_key, datestamp, region, service)
96
97# Sign the string_to_sign using the signing_key
98signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha512).hexdigest()
99
100
101# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
102# The signing information can be either in a query string value or in
103# a header named Authorization. This code shows how to use a header.
104# Create authorization header and add to request headers
105authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
106
107# The request can include any headers, but MUST include "host", "x-termcat-date",
108# and (for this scenario) "Authorization". "host" and "x-termcat-date" must
109# be included in the canonical_headers and signed_headers, as noted
110# earlier. Order here is not significant.
111# Python note: The 'host' header is added automatically by the Python 'requests' library.
112
113#headers = {'x-termcat-date': amzdate, 'Authorization': authorization_header}
114content_type = 'application/x-www-form-urlencoded; charset=utf-8'
115headers = {'x-termcat-content-sha512': payload_hash, 'x-termcat-date': termcatdate, 'Authorization': authorization_header, 'content-type': content_type}
116
117
118# ************* SEND THE REQUEST *************
119request_url = endpoint + '?' + canonical_querystring
120#request_url = endpoint + '/' + canonical_querystring
121
122print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
123print('Request URL = ' + request_url)
124start = time.time()
125r = requests.get(request_url, headers=headers)
126end = time.time()
127elapsed = end - start
128print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
129print('Response code: %d\n' % r.status_code)
130print(r.text.encode('utf-8'))
131print('Time spent: ' + str(elapsed) + ' s')