Use custom encryption
PubNub SDKs expose an interface for custom cryptors. Encryption and decryption logic is decoupled from the SDK, so you can plug in any algorithm alongside the built-in ones.
When the SDK decrypts a message or file, it reads a header in the payload and selects the matching cryptor automatically. This means a client can handle messages encrypted by different cryptors without extra logic in your app code.
Before you start
Confirm you have:
- A PubNub keyset with publish and subscribe keys from Admin Portal.
- Familiarity with your SDK's cryptor interface. See Cryptor interfaces by SDK for links.
Steps
Implement the cryptor interface
Each SDK defines a cryptor interface. Implement it with your custom algorithm. The method names vary by SDK, but every implementation must include an id that uniquely identifies the cryptor. In most SDKs this must be a value of exactly 4 bytes.
The example below uses Kotlin. The pattern is the same across all supported SDKs.
1
Create a CryptoModule with the custom cryptor
Pass your cryptor as the default when creating the CryptoModule, then pass the module to PubNub configuration.
1val customCryptor = myCustomCryptor()
2val cryptoModule = CryptoModule.createNewCryptoModule(defaultCryptor = customCryptor)
Pass cryptoModule to the PubNub configuration in the same way as the built-in AES-CBC module. See Encrypt and decrypt all messages and files for the initialization pattern.
Cryptor interfaces by SDK
Each SDK exposes the cryptor interface at a different location. Implement the interface listed for your SDK:
| SDK | Interface |
|---|---|
| C-Core (legacy) | pbcc_crypto.h |
| C# / Unity | ICryptor.cs |
| Dart | ICryptor.dart |
| Go | cryptor.go |
| Java | Cryptor.kt |
| JavaScript | ICryptor.ts |
| Kotlin | Cryptor.kt |
| Objective-C | PNCryptor.h |
| PHP | Cryptor.php |
| Python | crypto_core.py |
| Ruby | cryptor.rb |
| Rust | cryptor.rs |
| Swift | Cryptor.swift |
The Unreal Engine SDK doesn't support custom cryptors. Its crypto module accepts only the built-in UPubnubAesCryptor and UPubnubLegacyCryptor. For details, refer to Unreal Engine encryption.
For SDK-specific configuration details, see the Crypto module section in each SDK's configuration reference.