Skip to content

Instantly share code, notes, and snippets.

@GoodnessEzeokafor
Created August 19, 2025 10:25
Show Gist options
  • Save GoodnessEzeokafor/74c843989529a0e0acb0dff7ddcd8061 to your computer and use it in GitHub Desktop.
Save GoodnessEzeokafor/74c843989529a0e0acb0dff7ddcd8061 to your computer and use it in GitHub Desktop.
Transact Pay Encryption
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto.Util.Padding import pad
import xml.etree.ElementTree as ET
def encrypt_transact_pay_payload(data, encryption_key):
try:
if not data:
raise Exception("Data sent for encryption is empty")
print(data)
# Decode the Base64 string
decoded_bytes = base64.b64decode(encryption_key)
# Convert the decoded bytes to a string
decoded_string = decoded_bytes.decode("utf-8")
public_xml_key = decoded_string.split("!")[1]
modulus = getXmlComponent(public_xml_key, "Modulus")
exponent = getXmlComponent(public_xml_key, "Exponent")
modulus_bytes = base64.b64decode(modulus)
exponent_bytes = base64.b64decode(exponent)
# Create an RSA public key from Modulus and Exponent
key = RSA.construct(
(
int.from_bytes(modulus_bytes, byteorder="big"),
int.from_bytes(exponent_bytes, byteorder="big"),
)
)
# Initialize the Cipher for encryption
cipher = PKCS1_v1_5.new(key)
# Encrypt data
encrypted_bytes = cipher.encrypt(bytes(data, "utf-8"))
# Convert to base 64 string
encrypted_bytes_ = base64.b64encode(encrypted_bytes)
return encrypted_bytes_.decode("utf-8")
except Exception as e:
raise e
def getXmlComponent(xmlstring, _field):
try:
# Parse the XML string
root = ET.fromstring(xmlstring)
# Find elements with the specified field name
modulusElements = root.findall(_field)
modulusValue = ""
if modulusElements:
# Extract the Modulus value from the first element
modulusValue = modulusElements[0].text
else:
print("Modulus element not found.")
return modulusValue
except Exception as e:
# Handle exceptions (e.g., parsing errors)
print("Error:", str(e))
return ""
if __name__ == '__main__':
encrypted_payload = encrypt_transact_pay_payload(
json.dumps(payload),
TRANSACT_PAY_ENCRYPTION_KEY,
)
print(">>> encrypted_payload <<<")
print(encrypted_payload)
api_payload = {
"data": encrypted_payload,
}
# Determine the appropriate Smile ID API URL based on environment
# Check multiple environment indicators
base_url = self.get_base_url()
url = f"{base_url}/payment/order/create"
headers = {
"api-key": TRANSACT_PAY_PUBLIC_KEY,
"content-type": "application/json",
# add other headers as needed
}
print(">> headers <<<")
print(headers)
response = requests.post(url, json=api_payload, headers=headers)
response_data = response.json() # parse JSON content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment