Working in Binary

I’ve been trying to implement a web-client for a server (implemented in C/C++) that has to deal with a lot of encrypting and decrypting of data with Rijndael/AES. Obviously, the weapon of choice for the web-end is javascript (and a little bit of Flash XMLSockets via Aflax).

Unfortunately, another requirement is that the client must deal with Unicode perfectly. After all, in today’s international world, it’s just plain wrong to implement anything with purely 8-bit ASCII in mind. Specifically, in this implementation, the plaintext is encoded in utf-8, then encrypted in AES, followed by an encoding to base64. The web client is of course then responsible for receiving that base64 blob out of the XMLSocket and attempt to display the original plaintext properly.

It sounds easy enough, but the shopping for various open source parts took me longer than expected. In light of that, I’ve decided to document the various implementations I found useful.

The first step is to take that base64 blob and convert it to something useful. In C, we’d want to tear it down to 8-bit bytes in order to feed it to our AES implementation. Unfortunately, in JavaScript the notion of a byte is “nicely” abstracted away, so we’ll have to deal with strings. Using webtoolkits Base64 and Utf8 implementations, we can convert the blob to a garbled ASCII string. (i.e. 5Lit5paH -> 中文 -> [some unreadable 6-byte string] ). We can then feed this string into this Rijndael implementation. We’re now left with another string, which we can decode to JavaScripts internal Unicode representation. Voila!

The key to the particular Rijndael implementation I’ve chosen is that it has a well documented approach to dealing with bytes in JavaScript. In particular, it converts any ASCII string to its byte representation as an array of integers (i.e. “Hello” -> [104, 101, 108, 108, 111]) and then operates on those “bytes” following the AES algorithm. While this is slow, it is clearer than other implementations I’ve found.

Leave a Reply