Goal
I'm attempting to convert an API authentication algorithm written in C# to Python. It seems like my code is just about there but when I attempt to authenticate with the API I get a 400 status_code error, which makes me believe there is something wrong with the request syntax. My thought is that it's an issue with generating the HMACSHA256 signature. The format for the authorization header is: amx AccessKey:Signature:Timestamp
The Timestamp is epoch time and the signature is a HMAC, generated using the Access Key and Secret Key.
I have changed the secret key, api key, and request url for obvious reasons, but when I print the URL everything appears like it should be working. What am I missing?
C#
Here is the current C# code that works properly.
public string GenerateAuthString(){
string requestSignatureBase64String = string.Empty;
string signatureRawData = String.Format("{0}:{1}", _requestAccessKey, _requestTimestamp);
var secretKeyByteArray = Encoding.UTF8.GetBytes(_requestSecretKey);
byte[] signature = Encoding.UTF8.GetBytes(signatureRawData);
using (HMACSHA256 hmac = new HMACSHA256(secretKeyByteArray)){
byte[] signatureBytes = hmac.ComputeHash(signature);
requestSignatureBase64String = Convert.ToBase64String(signatureBytes);
}
string auth_string = "amx " + _requestAccessKey + ":" + requestSignatureBase64String + ":" + _requestTimestamp;
return (auth_string);
}
Python
Here is the Python code I'm working on.
import requests
import time
import hmac
import hashlib
import base64
def generate_auth():
requestAccessKey = '1a2b3c4'
requestSecretKey = '5c6b738'
requestTimestamp = int(time.time())
strTimestamp = str(requestTimestamp)
requestSignatureBase64String = ''
signatureRawData = '{} {}'.format(requestAccessKey, requestTimestamp)
secretKeyByteArray = bytearray(requestSecretKey, 'utf-8')
signature = bytearray(signatureRawData, 'utf-8')
# HMAC SHA256 Computation
signature = base64.b64encode(hmac.new(secretKeyByteArray, signature, digestmod=hashlib.sha256).digest())
signatureStr = str(signature)
authString = 'amx ' + requestAccessKey + ':' + signatureStr + ':' + strTimestamp
return(authString)
# Call function generating authentication string
auth = generate_auth()
r = requests.get('https://api.testing.online', params=auth)
print(r.url)