Create Encrypted Chat Messages
In this blog post, we’ll walk you through sending and receiving encrypted chat messages. We’ll demonstrate how Babel shares 1024-bit RSA public keys where chat participants will use these keys to send encrypted chat message. Along the way, we’ll also build a messaging system for encrypted chat messages with PubNub. Additionally the asymmetric encrypted payload will be delivered over XMPP and WebSocket streaming 2048-bit SSL TLS connects.
Here’s what we’ve covered so far:
- Part One: Set up a chat application and gave an overview of its architecture.
- Part Two: Built a key exchange system, enabling you to share public keys between users.
- Part Four: How to send self destructing chat messages
- Part Five: Building a chatroom UI
This is a five part series on building Babel, an open source chat widget and API built with PubNub. Babel allows you to send and receive self destructing, encrypted chat messages and exchange 1024-bit RSA public keys in a chatroom.
Check out the live working Babel self destructing chat demo. You can also take a look at the source code on our Babel Github Repository. Now, let’s get the tutorial started!
Sending Encrypted Chat Messages over WebSockets
[Read more on: MQTT]
We have to subscribe to a channel and set our state to our username and public key. While we’re subscribing, we’ll also declare two functions,
onPresence, which we’ll initialize later.
We can get the public keys of all users currently subscribed to a channel simply by calling
state enabled and then storing the data into our
users object, which contains a mapping of usernames to their public keys.
onPresence will be called whenever a user leaves or joins the
babel channel. So in order to keep
users up to date, we’ll call initialize
onPresence to call
here_now and update
users every time it’s called.
Step 3: Encrypted Chat Messaging over WebSockets
Now, let’s implement a function to send encrypted messages to other users.
sendMessage takes a username and a message to send. If
recipient is actually the username of a current user, then
sendMessage will encrypt the message with the recipient’s public key, which is stored in the
users object, and publish a message containing the username of the recipient, the sender, and the encrypted message.
Because we now know what form the messages will be in, we can initialize
onMessage to properly handle messages. For now, we’ll enable
onMessage so that it recognizes when we’ve received an encrypted message, decrypts the message with our private RSA key, and prints the decrypted message out into the console.
Sending Encrypted Chat Messages – Demo
That’s it! We’ve now built a key exchange system and walked you through how to send and receive encrypted messages. Next, we’ll show you how to self destruct your messages.