How to Encrypt WEB API request and response using PyCryptodome

sachin gupta 376 Reputation points
2023-02-03T02:08:26.36+00:00

Recently I come up a scenario where I need to encrypt a WEB API request and response using PyCryptodome inside Synapse notebook activity. I am trying to make a call to LinkedIn API, but the request should be encrypted and similarly response should be encrypted.

I looked many articles around this but not able to figure it out on how to do this. It would be really helpful if someone can give me idea or guide me on how I can achieve this.

Thank You!

Azure Synapse Analytics
Azure Synapse Analytics
An Azure analytics service that brings together data integration, enterprise data warehousing, and big data analytics. Previously known as Azure SQL Data Warehouse.
4,422 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Adrian Gallo 80 Reputation points
    2023-02-03T04:09:56.9666667+00:00

    You can use PyCryptodome to encrypt the request and response in a web API by following these steps:

    1. Generate a symmetric key and initialize vector (IV): You can use a symmetric encryption algorithm such as AES to encrypt your request and response. Generate a random symmetric key and IV.
    2. Encrypt the request: Use the symmetric key and IV to encrypt the request. You can use the AES.new method from the PyCryptodome library to encrypt the request data.
    3. Send the encrypted request: Add the encrypted request, the symmetric key, and IV to the header of the HTTP request.
    4. Decrypt the response: On the server side, extract the symmetric key and IV from the header and use them to decrypt the response.
    5. Return the decrypted response: Return the decrypted response to the client.

    Here's some SCSS code to show how PyCryptodome can be used to encrypt and decrypt data:

    
    from Crypto.Cipher import AES
    import base64
    
    def encrypt_data(key, data):
        BS = AES.block_size
        pad = lambda s: s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)).encode()
        cipher = AES.new(key, AES.MODE_CBC, iv)
        encrypted_data = base64.b64encode(cipher.encrypt(pad(data)))
        return encrypted_data
    
    def decrypt_data(key, encrypted_data):
        BS = AES.block_size
        unpad = lambda s : s[:-ord(s[len(s)-1:])]
        cipher = AES.new(key, AES.MODE_CBC, iv)
        decrypted_data = unpad(cipher.decrypt(base64.b64decode(encrypted_data)))
        return decrypted_data