Response Data Validation


You can validate the response data of all service APIs and its integrity through HMAC. With every successful Service API response, a header with key "hmac" contains the HMAC digest value. You can calculate the HMAC digest of the response body, and then compare it to the digest in the header.

Calculation

Steps:

  1. Sort the fields inside the "result" object by key in ascending alphabetical order (Lexicographical order)

  2. Concatenate the ordered values into a single string (No separators)

  3. Sort the fields inside the response body in lexicographical order.

  4. Concatenate the ordered values into a single string (No separators)

  5. Calculate the HMAC digest of the using SHA512 and the bundle’s HMAC key. HMAC Key will be provided separate from the documentation.

  6. Convert the digest into Hexadecimal Lowercase format.

  7. Compare the resulting digest with the one in the response header.

Example:

Consider the following response for the Egyptian National ID OCR:

hmac_key = "secret_key"

response_data = {
  "result": {
    "back_nid": "back_nid",
    "date_of_birth": "date_of_birth",
    "expiry_date": "expiry_date",
    "gender": "gender",
    "husband_name": "husband_name",
    "marital_status": "marital_status",
    "profession": "profession",
    "release_date": "release_date",
    "religion": "religion",
    "area": "area",
    "first_name": "first_name",
    "front_nid": "front_nid",
    "full_name": "full_name",
    "serial_number": "serial_number",
    "street": "street"
  },
  "transaction_id": "transaction_id",
  "trials_remaining": 3,
}

concatenated_string = "areaback_niddate_of_birthexpiry_datefirst_namefront_nidfull_namegenderhusband_namemarital_statusprofessionrelease_datereligionserial_numberstreettransaction_id3"

calculated_digest = "d3f33383a5eae30125523bc8e6bdfbbe08cec2d87fb6f54e273e78faeec2fbc0f652d8e5f183729c3de405863018f9309f25b8000f3ca925d3efafdd4d4c0b70"

Code Snippets

import hashlib
import hmac
from collections import OrderedDict

def concatenate_dict(data_dict):
    od = OrderedDict(sorted(data_dict.items()))
    message = ''
    for _, v in od.items():
        if type(v) is dict:
            message += concatenate_dict(v)
        elif type(v) is bool:
            message += str(v).lower()
        elif v is None:
            message += 'null'
        else:
            message += str(v)

    return message

def calculate_digest(response_data, hmac_key):
    # Convert dict to string
    message = concatenate_dict(response_data)

    # Compute HMAC using SHA512
    calculated_hmac = hmac.new(
        hmac_key.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha512
    ).hexdigest().lower()

    return calculated_hmac
    
response_data = {
    # Service API Response Data
}
hmac_key = "<hmac-key>"

print(calculate_digest(response_data, hmac_key))

Last updated