Python Encryption Sample Code

from Crypto.Cipher 
import AES
import json
import binascii




# Convert hexadecimal string to bytes
def hex_to_bytes(hex_string):
   return binascii.unhexlify(hex_string)




# Convert bytes to hexadecimal string
def bytes_to_hex(byte_data):
   return binascii.hexlify(byte_data).decode()




# Encrypt function
def encrypt(data: str, key_hex: str, iv_hex: str):
   # Convert hex key and IV to bytes 
   key = hex_to_bytes(key_hex)
   iv = hex_to_bytes(iv_hex)


   # Ensure data is a multiple of the block size (16 bytes) by padding
   data_bytes = data.encode()  # Convert to bytes
   padding_length = 16 - (len(data_bytes) % 16)  # Calculate padding size
   padded_data = data_bytes + bytes(
       [padding_length] * padding_length)  # Add padding


   # Perform AES encryption (with truncated or custom IV)


   cipher = AES.new(key, AES.MODE_CBC, iv)
   encrypted_bytes = cipher.encrypt(padded_data)


   # Convert encrypted bytes to hex
   return bytes_to_hex(encrypted_bytes)




# Decrypt function
def decrypt(encrypted_hex: str, key_hex: str, iv_hex: str):
   # Convert hex key, IV, and encrypted data to bytes
   key = hex_to_bytes(key_hex)
   iv = hex_to_bytes(iv_hex)
   encrypted_bytes = hex_to_bytes(encrypted_hex)


   # Perform AES decryption (with truncated or custom IV)


   cipher = AES.new(key, AES.MODE_CBC, iv)
   decrypted_padded = cipher.decrypt(encrypted_bytes)


   # Remove padding  # Remove padding
   padding_length = decrypted_padded[-1]  # Last byte indicates padding size
   decrypted_data = decrypted_padded[:-padding_length]  # Remove padding


  # Convert bytes to string  
   return decrypted_data.decode()




  # Example usaget 
if __name__ == "__main__":
   # Define key and IV in hex format (must match PHP values)
   key_hex = "97b7a43a0e70b4e73a157670151671903ebc1ec1843e78a06ea6e0f85d60048d"  # 32 bytes hex
   iv_hex = "db3777f596e190fadb3777f596e190fa"  # 16 bytes hex


   
    # Data to encrypt 
   plaintext = {
       "p1": "212201508185",
       "p2": "ICIC0002122",
       "p3": "UB456787654",
       "p4": "61a",
       "p5": "DEV",
       "p6": "9090686809",
       "p7": "dev.pandey@nerasoft.in",
       "p8": "ravi",
       "p9": "vendor payment",
       "p10": "27.1111,54.1111"
   }
   plaintext_json = json.dumps(plaintext)


    Encrypt 
   encrypted_hex = encrypt(plaintext_json, key_hex, iv_hex)
   print("Encrypted (Hex):", encrypted_hex)


    Decrypt 
   decrypted_text = decrypt(encrypted_hex, key_hex, iv_hex)
   print("Decrypted Text:", decrypted_text)