Encryption API for Swift Native SDK

PubNub Swift Native SDK includes message encryption. This page explains how to configure the cryptoModule and how to encrypt and decrypt data. The SDK supports 128-bit Advanced Encryption Standard (AES) and 256-bit AES in Cipher Block Chaining (CBC) mode (AES-CBC).

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

Configuration​

cryptoModule configuration​

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

1

1

Your client can decrypt content produced by either cryptoModule or legacy cipherKey-based encryption. This allows the client to read historical messages and messages from older clients while you encrypt new messages with the stronger AES-256-CBC cipher.

Older SDK versions

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

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.

Relationship between cryptoModule and cipher keys​

The cryptoModule supersedes cipher-key parameters. Passing a direct cipher key to a method (where available) overrides the configured cryptoModule for that operation and uses legacy AES-128 encryption. For partial encryption, create a separate cryptoModule instance and use it only where needed.

Encryption methods​

Encrypt​

Use this function to encrypt data.

Availability

For more information, refer to Crypto module configuration.

Method(s)​

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

1func encrypt(data: Data)
* required
ParameterDescription
data *
Type: Data
The message to encrypt.

Sample code​

Encrypt part of message​
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.
1

Returns​

Success​

Encrypted Data received from the Foundation object.

Failure​

An Error describing the failure.

Decryption methods​

Decrypt​

Use this function to decrypt data.

Availability

For more information, refer to Crypto module configuration.

Method(s)​

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

1func decrypt(data: Data) -> Result<Data, Error>
* required
ParameterDescription
data *
Type: Data
The data to decrypt.

Sample code​

Decrypt part of message​
1

Returns​

Success​

Initial Data which has been encrypted earlier.

Failure​

An Error describing the failure.

Was this page useful?

Last updated on