Encryption API for Rust SDK
PubNub Rust SDK includes message encryption. This page shows how to set up the crypto module and perform partial encryption. The SDK supports 128-bit Advanced Encryption Standard (AES) and 256-bit AES in Cipher Block Chaining (CBC) mode.
For general SDK configuration and initialization, refer to the Configuration page.
Configuration
CryptoModule
CryptoModule implements the CryptoProvider trait and provides encrypt/decrypt functionality for messages. From the 0.3.0 onward, you can configure the algorithms it uses.
Each PubNub SDK is bundled with two ways of encryption: the legacy encryption with 128-bit cipher key entropy and the recommended 256-bit AES-CBC encryption. For more general information on how encryption works, refer to Message Encryption.
The default constructors for the bundled crypto modules take the cipher_key (string used to encrypt/decrypt) and use_random_iv (boolean, whether or not to use a random initialization vector) parameters as arguments.
Legacy encryption with 128-bit cipher key entropy
You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.
SDK initialization required
Before you use encryption methods, ensure your PubNub client is configured with a subscribe key and a user ID. See the Configuration guide for setup instructions.
CryptoModule configuration
To configure the CryptoModule to encrypt all messages/files, you can use the following methods in the Rust SDK:
// encrypts using 256-bit AES-CBC cipher (recommended)
// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers
let client = PubNubClientBuilder::with_transport(Transport)
...
.with_cryptor(CryptoModule::new_aes_cbc_module("enigma", true)?)
.build()?;
// encrypts with 128-bit cipher key entropy (legacy)
// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers
let client = PubNubClientBuilder::with_transport(Transport)
...
.with_cryptor(CryptoModule::new_legacy_module("enigma", true)?)
.build()?;
The client can decrypt content from either module. You can read historical messages and messages from older clients, and you can encrypt new messages with 256-bit AES-CBC.
Older SDK versions
Apps built using the SDK versions lower than 0.3.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.
Partial encryption
For partial encryption of individual strings, you can create a crypto module instance and use it directly:
Sample code
Reference code
// partial encryption
// creates an instance
crypto_module = CryptoModule::new_aes_cbc_module("enigma", true)?;
// encrypts a string
let encrypt_result = crypto_module.encrypt(b"string to encrypt")?;
// decrypts a string
crypto_module.decrypt(encrypt_result)?;