---
source_url: https://www.pubnub.com/docs/sdks/go/api-reference/encryption
title: Encryption API for Go SDK
updated_at: 2026-06-19T11:37:23.701Z
sdk_name: PubNub Go SDK
sdk_version: v9.0.1
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Encryption API for Go SDK

PubNub Go SDK, use the latest version: v9.0.1

Install:

```bash
go get github.com/pubnub/go/v9@v9.0.1
```

PubNub Go SDK includes message and file encryption. This page shows how to set up the crypto module 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.

For general SDK configuration and initialization, refer to the [Configuration](https://www.pubnub.com/docs/sdks/go/api-reference/configuration) page.

## Configuration

### CryptoModule configuration

To configure the `CryptoModule` to encrypt all messages/files, you can use the following methods in the Go SDK:

```go
// encrypts using 256 bit AES-CBC cipher (recommended)
// decrypts data encrypted with the legacy and the 256 bit AES-CBC ciphers
config.CryptoModule = crypto.NewAesCbcCryptoModule("cipherKey", true)

// encrypts with 128-bit cipher key entropy (legacy)
// decrypts data encrypted with the legacy and the 256 bit AES-CBC ciphers
config.CryptoModule = crypto.NewLegacyModule("cipherKey", true)
```

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.

:::warning Older SDK versions
Apps built using the SDK versions lower than 7.1.2 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.
:::

:::note 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](https://www.pubnub.com/docs/sdks/go/api-reference/configuration#initialization) for setup instructions.
:::

## Encryption methods

### Encrypt

Use this function to encrypt data.

:::warning Deprecated
The `key` parameter in this method is deprecated. We recommend that you configure a separate instance of the [crypto module](https://www.pubnub.com/docs/sdks/go/api-reference/configuration#cryptomodule) and use it for partial encryption. If you pass `cipherKey` as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.
:::

#### Method(s)

```go
utils.EncryptString(cipherKey, string, useRandomInitializationVector)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| cipherKey | string | Yes |  | Cipher key to use for decryption. If no key is provided, Cipher key provided in `PNConfiguration` will be considered. |
| string | string | Yes |  | The data to encrypt |
| useRandomInitializationVector | boolean | Yes |  | When true the initialization vector (IV) is random for all requests (not just for file upload). When false the IV is hard-coded for all requests except for file upload. |

#### Sample code

:::tip 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.
:::

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_encryptDecryptString demonstrates encrypting and decrypting a string directly
func Example_encryptDecryptString() {
	// Create a crypto module
	cryptoModule, err := crypto.NewAesCbcCryptoModule("my-cipher-key", true)
	if err != nil {
		fmt.Printf("Error creating crypto module: %v\n", err)
		return
	}

	// Original message
	originalMessage := "This is a sensitive message"

	// Encrypt the message
	encryptedData, err := cryptoModule.Encrypt([]byte(originalMessage))
	if err != nil {
		fmt.Printf("Error encrypting: %v\n", err)
		return
	}

	fmt.Println("Message encrypted successfully")

	// Decrypt the message
	decryptedData, err := cryptoModule.Decrypt(encryptedData)
	if err != nil {
		fmt.Printf("Error decrypting: %v\n", err)
		return
	}

	fmt.Printf("Decrypted message: %s\n", string(decryptedData))

	// Output:
	// Message encrypted successfully
	// Decrypted message: This is a sensitive message
}
```

### Encrypt file

Use this function to encrypt file content using the CryptoModule.

#### Method(s)

To encrypt a file stream, you can use the following method in Go SDK:

```go
module.EncryptStream(input io.Reader) (io.Reader, error)
```

| Parameter | Description |
| --- | --- |
| `input` *Type: io.Reader | Reader to read the file or data stream to encrypt. |

#### Returns

`io.Reader` with encrypted data, and an error if encryption fails.

#### Sample code

:::tip 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.
:::

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"io"
	"os"
	pubnub "github.com/pubnub/go/v9"
)

// encryptStream demonstrates encrypting a data stream
func encryptStream() {
	// Create a crypto module with your cipher key
	module, err := crypto.NewAesCbcCryptoModule("your-cipher-key", true)
	if err != nil {
		panic(err)
	}

	// Open the file you want to encrypt (or any io.Reader)
	inputFile, err := os.Open("path/to/your/file.jpg")
	if err != nil {
		// File doesn't exist - this is just an example
		return
	}
	defer inputFile.Close()

	// Encrypt the stream - returns an io.Reader with encrypted data
	encryptedStream, err := module.EncryptStream(inputFile)
	if err != nil {
		panic(err)
	}

	// Write the encrypted stream to an output file
	outputFile, _ := os.Create("encrypted_output.jpg")
	defer outputFile.Close()
	io.Copy(outputFile, encryptedStream)
}
```

## Decryption methods

### Decrypt

Use this function to decrypt data.

:::warning Deprecated
The `cipherKey` parameter in this method is deprecated. We recommend that you configure a separate instance of the [crypto module](https://www.pubnub.com/docs/sdks/go/api-reference/configuration#cryptomodule) and use it for partial encryption. If you pass `cipherKey` as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.
:::

#### Method(s)

```go
utils.DecryptString(cipherKey, encrypted, useRandomInitializationVector)
```

| Parameter | Description |
| --- | --- |
| `cipherKey` *Type: string | Cipher key to use for decryption. If no key is provided, Cipher key provided in `PNConfiguration` will be considered. |
| `encrypted` *Type: string | The data to decrypt |
| `useRandomInitializationVector` *Type: boolean | When set to `true`, the initialization vector (IV) is random for all requests, not just for file upload. When set to `false`, the IV is hard-coded for all requests except for file upload. |

#### Sample code

:::tip 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.
:::

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// decryptString demonstrates decrypting a string
func decryptString() {
	// Create a crypto module with your cipher key (must match encryption key)
	module, err := crypto.NewAesCbcCryptoModule("your-cipher-key", true)
	if err != nil {
		panic(err)
	}

	// Your encrypted data (replace with actual encrypted bytes)
	encryptedData := []byte("your-encrypted-data-here")

	// Decrypt the data
	decryptedBytes, err := module.Decrypt(encryptedData)
	if err != nil {
		panic(err)
	}

	// Convert decrypted bytes back to string
	decryptedMessage := string(decryptedBytes)
	_ = decryptedMessage
	// Now you can use decryptedMessage
}
```

### Decrypt file

Use this function to decrypt file content using the CryptoModule.

#### Method(s)

To decrypt a file stream, you can use the following method in Go SDK:

```go
module.DecryptStream(input io.Reader) (io.Reader, error)
```

| Parameter | Description |
| --- | --- |
| `input` *Type: io.Reader | Reader to read the encrypted file or data stream. |

#### Returns

`io.Reader` with decrypted data, and an error if decryption fails.

#### Sample code

:::tip 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.
:::

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"io"
	"os"
	pubnub "github.com/pubnub/go/v9"
)

// decryptStream demonstrates decrypting a data stream
func decryptStream() {
	// Create a crypto module with your cipher key (must match encryption key)
	module, err := crypto.NewAesCbcCryptoModule("your-cipher-key", true)
	if err != nil {
		panic(err)
	}

	// Open the encrypted file (or any io.Reader with encrypted data)
	encryptedFile, err := os.Open("path/to/encrypted_output.jpg")
	if err != nil {
		// File doesn't exist - this is just an example
		return
	}
	defer encryptedFile.Close()

	// Decrypt the stream - returns an io.Reader with decrypted data
	decryptedStream, err := module.DecryptStream(encryptedFile)
	if err != nil {
		panic(err)
	}

	// Write the decrypted stream to an output file
	outputFile, _ := os.Create("decrypted_file.jpg")
	defer outputFile.Close()
	io.Copy(outputFile, decryptedStream)
}
```

## Other examples

### Publish encrypted message

This example shows how to publish an encrypted message using the `CryptoModule`:

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_publishEncryptedMessage demonstrates publishing an encrypted message using CryptoModule
func Example_publishEncryptedMessage() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo" // Replace with your subscribe key
	config.PublishKey = "demo"   // Replace with your publish key

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	// Create a crypto module for encryption
	cryptoModule, _ := crypto.NewAesCbcCryptoModule("my-secret-key", true)
	config.CryptoModule = cryptoModule

	pn := pubnub.NewPubNub(config)

	// Publish an encrypted message
	response, status, err := pn.Publish().
		Channel("encrypted-channel").
		Message("This is a secret message!").
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 && response.Timestamp > 0 {
		fmt.Println("Encrypted message published successfully")
	}

	// Output:
	// Encrypted message published successfully
}
```

### Subscribe to encrypted messages

This example shows how to subscribe to a channel and automatically decrypt incoming messages:

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_subscribeEncryptedMessage demonstrates receiving and decrypting messages
func Example_subscribeEncryptedMessage() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	// Create a crypto module with the same key used for encryption
	cryptoModule, _ := crypto.NewAesCbcCryptoModule("my-secret-key", true)
	config.CryptoModule = cryptoModule

	pn := pubnub.NewPubNub(config)

	// Create listener to receive messages
	listener := pubnub.NewListener()

	// Create a done channel to stop the goroutine when needed
	done := make(chan bool)

	// snippet.hide
	messageReceived := make(chan bool)
	// snippet.show

	go func() {
		for {
			select {
			case status := <-listener.Status:
				// snippet.hide
				if status.Category == pubnub.PNConnectedCategory {
					// Once connected, publish the encrypted message
					pn.Publish().
						Channel("encrypted-sub-channel").
						Message("Secret data").
						Execute()
				}
				// snippet.show

			case message := <-listener.Message:
				// Message is automatically decrypted
				fmt.Printf("Received decrypted message: %v\n", message.Message)
				// snippet.hide
				messageReceived <- true
				// snippet.show
				return

			case <-done:
				return
			}
		}
	}()

	pn.AddListener(listener)

	pn.Subscribe().
		Channels([]string{"encrypted-sub-channel"}).
		Execute()

	fmt.Println("Subscribed to encrypted channel")

	// snippet.hide
	// Wait for message with timeout
	select {
	case <-messageReceived:
		// Message received successfully
	case <-time.After(15 * time.Second):
		fmt.Println("Timeout - prevent hanging")
		// Timeout - prevent hanging
	}
	// snippet.show

	// When done, unsubscribe and stop goroutine
	pn.UnsubscribeAll()
	close(done)

	// Output:
	// Subscribed to encrypted channel
	// Received decrypted message: Secret data
}
```

### Publish encrypted JSON data

This example demonstrates encrypting complex JSON data structures:

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_publishEncryptedJSON demonstrates encrypting JSON data
func Example_publishEncryptedJSON() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	// Create crypto module
	cryptoModule, _ := crypto.NewAesCbcCryptoModule("my-secret-key", true)
	config.CryptoModule = cryptoModule

	pn := pubnub.NewPubNub(config)

	// Publish encrypted JSON data
	userData := map[string]interface{}{
		"userId":   "user123",
		"email":    "user@example.com",
		"balance":  1000.50,
		"verified": true,
	}

	response, status, err := pn.Publish().
		Channel("encrypted-json-channel").
		Message(userData).
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 && response.Timestamp > 0 {
		fmt.Println("Encrypted JSON published successfully")
	}

	// Output:
	// Encrypted JSON published successfully
}
```

### Fetch encrypted message history

This example shows how to retrieve encrypted messages from history. Messages are automatically decrypted:

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_historyWithEncryption demonstrates fetching encrypted message history
func Example_historyWithEncryption() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	// Create crypto module
	cryptoModule, _ := crypto.NewAesCbcCryptoModule("my-history-key", true)
	config.CryptoModule = cryptoModule

	pn := pubnub.NewPubNub(config)

	// Publish an encrypted message
	pn.Publish().
		Channel("history-encrypted-channel").
		Message("Encrypted historical message").
		Execute()

	// Fetch history - messages will be automatically decrypted
	response, status, err := pn.History().
		Channel("history-encrypted-channel").
		Count(10).
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 && len(response.Messages) > 0 {
		fmt.Println("Fetched encrypted message history")
		// Messages are automatically decrypted
		fmt.Printf("First message: %v\n", response.Messages[0].Message)
	}

	// Output:
	// Fetched encrypted message history
	// First message: Encrypted historical message
}
```

### Use different encryption keys for different channels

This example demonstrates using multiple PubNub instances with different encryption keys:

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_multipleCryptoModules demonstrates using different encryption for different channels
func Example_multipleCryptoModules() {
	// Create first PubNub instance with one encryption key
	config1 := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user-1"))
	config1.SubscribeKey = "demo"
	config1.PublishKey = "demo"

	// snippet.hide
	config1 = setPubnubExampleConfigData(config1)
	// snippet.show

	cryptoModule1, _ := crypto.NewAesCbcCryptoModule("key-for-channel-1", true)
	config1.CryptoModule = cryptoModule1

	pn1 := pubnub.NewPubNub(config1)

	// Create second PubNub instance with different encryption key
	config2 := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user-2"))
	config2.SubscribeKey = "demo"
	config2.PublishKey = "demo"

	// snippet.hide
	config2 = setPubnubExampleConfigData(config2)
	// snippet.show

	cryptoModule2, _ := crypto.NewAesCbcCryptoModule("key-for-channel-2", true)
	config2.CryptoModule = cryptoModule2

	pn2 := pubnub.NewPubNub(config2)

	// Publish to different channels with different encryption
	response1, status1, err1 := pn1.Publish().
		Channel("secure-channel-1").
		Message("Message for channel 1").
		Execute()

	response2, status2, err2 := pn2.Publish().
		Channel("secure-channel-2").
		Message("Message for channel 2").
		Execute()

	if err1 == nil && err2 == nil &&
		status1.StatusCode == 200 && status2.StatusCode == 200 &&
		response1.Timestamp > 0 && response2.Timestamp > 0 {
		fmt.Println("Messages published with different encryption keys")
	}

	// Output:
	// Messages published with different encryption keys
}
```

### Using legacy CipherKey configuration (deprecated)

This example shows the deprecated way of configuring encryption. Use `CryptoModule` instead for new applications:

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"

	pubnub "github.com/pubnub/go/v9"
)

// Example_legacyCipherKey demonstrates using the legacy CipherKey configuration (deprecated)
func Example_legacyCipherKey() {
	config := pubnub.NewConfigWithUserId(pubnub.UserId("demo-user"))
	config.SubscribeKey = "demo"
	config.PublishKey = "demo"

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	// Using CipherKey (deprecated - use CryptoModule instead)
	config.CipherKey = "my-cipher-key"

	pn := pubnub.NewPubNub(config)

	// Messages will be automatically encrypted/decrypted
	response, status, err := pn.Publish().
		Channel("legacy-encrypted-channel").
		Message("Legacy encrypted message").
		Execute()

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	if status.StatusCode == 200 && response.Timestamp > 0 {
		fmt.Println("Message published with legacy encryption")
	}

	// Output:
	// Message published with legacy encryption
}
```

## Terms in this document

* **Subscribe Key** - A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.
* **User** - An individual or entity that interacts with a system, application, or service. In PubNub, a user typically refers to someone who sends or receives messages through the platform, identified by a unique user ID or username.
* **User ID** - UTF-8 encoded, unique string of up to 92 characters used to identify a single client (end user, device, or server) that connects to PubNub.