Python Cryptography - Encryption and Decryption

Symmetric encryption and decryption with Fernet keys shared by all servers in an environment.

The API below allows for symmetric encryption and decryption using configurable secret keys. After encryption, the data returned is safe to use in URLs.

The keys are generated when servers are created. Access to the keys must be restricted because knowledge of keys lets anyone decrypt any previously encrypted data.

If there is more than one server in an environment, all of them must use the same secret key.

Note that the output of encryption contains the timestamp indicating when it took place. Because a timestamp is included, each generated secret will be different even for the same input data.

Under the hood, encryption and decryption are implemented using Fernet (AES-128, PKCS7, HMAC-SHA256).

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class MyService(Service):
    def handle(self):

        # Data to encrypt - note that it must be a bytes object
        data = b'1234567890'

        # Log data to be manipulated
        self.logger.info('Data `%s`', data)

        # Encrypt it
        encrypted = self.crypto.encrypt(data)

        # Log the resulting form
        self.logger.info('Encrypted `%s`', encrypted)

        # Decrypt it back
        decrypted = self.crypto.decrypt(encrypted)

        # Log output - will be the same as original data
        self.logger.info('Decrypted `%s`', decrypted)
INFO - Data `1234567890`
INFO - Encrypted `gAAAAABaxzkr2Rizsro...`
INFO - Decrypted `1234567890`

Other crypto APIs: