0

I need to generate a HmacSHA256 signature using python with the following parameters to the signature:

merchantId = "testMerchantExample"
apiHost = "apitest.example.com" 
apiUrl = "/v1/example?startDate=2019-07-01&organizationId=" + merchantId  

keyId = "KeyIdHere"
keyString = "KeyStringHere"

signatureParams = "host: "+apiHost+"\n"
        + "date: " + date + "\n"
        + "(request-target): get "+apiUrl+"\n"
        + "merchant-id: " + merchantId

These parameters need to then be passed into the function to generate the SHA256 signature.

I dont know how to do this in Python 2.7, I have seen some examples generating signatures etc. But none with these parameters. They use the following python libs:

import hmac import hashlib

Any help would be appreciated.

Here is code that I found online, it works and generated the signature correctly yay:

import hmac
import hashlib 
import binascii

def create_sha256_signature(key, message):
    byte_key = binascii.unhexlify(key)
    message = message.encode()
    return hmac.new(byte_key, message, hashlib.sha256).hexdigest().upper()
Jamie
  • 11
  • 3

1 Answers1

0

For Python2.7+ , you can use below solution to generate sha256 algorithm signature :

import hashlib

def get_sign(s):
    h = hashlib.sha256()
    h.update(s.encode('utf-8'))
    return h.hexdigest()

sign = get_sign(APP_ID+input_str+salt+curtime+APP_SECRET)
print('sign: ', sign)

Output:

sign:  510f6f68b56caf56c7da770d1a4db8b9c46f4286cda052c699ed05637bd53517
Lin Du
  • 88,126
  • 95
  • 281
  • 483