> For the complete documentation index, see [llms.txt](https://docs.dpsn.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.dpsn.org/integration/private-messaging.md).

# Private Messaging

In DPSN, private messaging involves a two-step process:

1. **Key Exchange:** The publisher initially sends an encrypted key to the subscriber.
2. **Message Encryption:** Subsequent messages are encrypted using this shared key.

### Integrating with the DPSN SDK

**Publisher Side**

1. **Create a Private Message Channel:** While creating a new stream, set Visibility = Private Stream. Before starting, register on DPSN Dashboard to start registration as publisher and obtain your **publisher access token** (Auto-generated on registration) by clicking the top-right menu → Access Tokens to view your publisher access token.
2. **Encrypt and Send Messages:** Share the private topic ID with the intended recipient

```
JavaScript

const DPSN = require('dpsn-sdk');

// Create a publisher instance and publish keys
const publisherPrivateChannel = new DPSN.Publisher(process.env.DPSN_DELEGATED_ADDRESS_PVTKEY, 'your_topic');
// Publish key
await publisherPrivateChannel.createPrivateChannel();
// Publish a message
publisherPrivateChannel.publishPrivateMessage(message);
```

**Subscriber Side**

1. **Subscribe to the Topic:** Subscribe to the topic where the public key was published.
2. **Receive and Store Public Key:** The SDK will automatically handle receiving and storing the public key.
3. **Decrypt Messages:** Use the `decryptPrivateMessage` function to decrypt incoming messages on the topic.

```
JavaScript

const DPSN = require('dpsn-sdk');

// Create a subscriber instance
const subscriber = new DPSN.Subscriber(process.env.DPSN_DELEGATED_ADDRESS_PVTKEY, 'your_topic');

// Subscribe to the topic
subscriber.subscribeToTopic('your_topic', (message) => {
  // Decrypt the message. The first key message will return null
  const decryptedMessage = subscriber.decryptPrivateMessage(message);
  if(decryptedMessage) process(decryptedMessage);
});
```

#### Key Features and Benefits

* **Simplified Integration:** The SDK handles key generation, encryption, and decryption, making it easy to implement private messaging.
* **Security:** DPSN ensures the security of private messages through robust encryption and key management.
* **Scalability:** The system can handle a large number of private messages and subscribers.
* **Flexibility:** Publishers can create multiple private channels and control access to them.
