|
Enabling Encryption |
|
Before you read
Overview
In this brief tutorial we look at what it takes to enable encryption in an ElectroServer application. While the example and code here are ActionScript 3, the technique is the same across all APIs. The example used here is just a modified version of the Simple Chat example. As such, we’ll only look at the portions of code relevant to encryption.
How it works
By default encryption is not enabled in an ElectroServer application. It can be enabled for one or more of the connections that the client currently has established with the server. The following line of code enables encryption.
The first time encryption is enabled the client and the server will go through a secure key exchange process in the background which generally takes about 1 second. Once this process is complete and encryption is ready to be used, the API fires off this event: EncryptionStateChangeEvent. The event object contains a property indicating the state of encryption.
It is important that no messages are sent to the server during this short time between enabling encryption and receiving the state change event. But once the event is received, the client can send and receive messages in exactly the same way as if encryption were not enabled. All messages will be encrypted.
To disable encryption use the same method used to enable it, but with a parameter of false, and watch for the state change event to know when it the change has taken effect.
The code
Let’s now look at how we took the Simple Chat example and made it into an encrypted ElectroServer application. Open Main.mxml and look at the onConnectionResponse event handler.
Instead of showing the login panel as a result of connecting, we enable encryption. Note that encryption can be enabled or disabled at any time – it doesn’t have to be done before logging in. But in this case we do it before logging in and gain the benefit of having the login details being encrypted.
There are a handful of events that we add listeners for in the onCreationComplete method. One of them is the state change event discussed above.
The onEncryptionStateChange event handler will be fired whenever the encryption state changes. In this application we only enable encryption and never disable it, so it will only be called once.
In the event handler above we simply log the encryption state, and then show the login panel. As soon as this event occurs the API is ready for you to send and receive encrypted messages.