Encryption API for Python SDK

PubNub Python SDK provides built-in message and file encryption to secure your real-time communications. This documentation covers crypto module configuration and utility methods for encrypting and decrypting files using both legacy 128-bit and enhanced 256-bit AES-CBC encryption.

For general SDK configuration and initialization, refer to the Configuration page.

Configuration

crypto_module configuration

To configure the crypto_module to encrypt all messages/files, you can use the following methods in the Python SDK:

#  encrypts using 256-bit AES-CBC cipher (recommended)
# decrypts data encrypted with the legacy (AES and GCM) and the 256-bit AES-CBC ciphers
config = PNConfiguration()
...
# all necessary config options
config.cipher_key = "my_cipher_key"
config.cipher_mode = AES.MODE_GCM # optional, used for the legacy module only
config.fallback_cipher_mode = AES.MODE_CBC # optional, used for the legacy module only
config.crypto_module = AesCbcCryptoModule(config)
pubnub = PubNub(config)

# encrypts with 128-bit cipher key entropy (legacy) with GCM
# decrypts data encrypted with the legacy (AES and GCM) and the 256-bit AES-CBC ciphers
config = PNConfiguration()
...
show all 33 lines

Your client can decrypt content encrypted using either of the modules. This way, you can interact with historical messages or messages sent from older clients while encoding new messages using the more secure 256-bit AES-CBC cipher.

Older SDK versions

Apps built using the SDK versions lower than 7.2.0 will not be able to decrypt data encrypted using the 256-bit AES-CBC cipher. Make sure to update your clients or encrypt data using the legacy algorithm.

SDK Initialization required

Before using encryption methods, ensure your PubNub client is properly configured with subscribe key and user ID. See the Configuration guide for setup instructions.

Encryption methods

Encrypt file

This function allows to encrypt the data.

Method(s)

To encrypt the data you can use the following method(s) in Python SDK.

pubnub.crypto.encrypt_file(file)
* required
ParameterDescription
file *
Type: bytes
The file to encrypt.

Sample code

Reference code

This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.

payload_to_encrypt = 'knights_who_say_ni'

encrypted_payload = pubnub.encrypt(payload_to_encrypt)

Returns

Bytes object with encrypted data.

Decryption methods

Decrypt file

This function allows to decrypt the data.

Method(s)

To decrypt the data you can use the following method(s) in Python SDK.

pubnub.crypto.decrypt_file(file)
* required
ParameterDescription
file *
Type: bytes
The file to decrypt.

Sample code

decrypted_payload = pubnub.decrypt(payload_to_decrypt_in_bytes)

Returns

Bytes object with decrypted data.

Last updated on