By removing all of the comments and whitespace and changing the names of the variable and internal functions I have managed to produce a version of his script that is only 6.6k in size (1/3 the size of his original) which is just about small enough to make it practical to attach to a web page. His script also has a byteArrayToString() function but no stringToByteArray() function and so I have also added the latter function to the code. I have also added a random key generator to the code for generating random numbers that can be used as passwords.
There are two steps involved with using this encryption algorithm. The first step is to use it to encrypt content and the second step is to use it with that encrypted content in order to allow the original content to be restored. With my extra function added, there are two ways that we can save the encrypted content. We can save it either as a series of hexadecimal values (where the encrypted content will be double the length of the original) or we can store it as a string which will be about the same length as the original but which will contain characters that will be considered to be invalid in certain situations.
Let's begin by looking at how you would write the code to convert a simple text string into its encrypted equivalent.
var plaintext = "Happy Birthday!";
var key = hexToByteArray(genkey());
var mode = 'ECB'; // ECB or CBC
var ciphertext =
This code will convert the text "Happy Birthday!" into an encrypted string using a randomly generated password. We will need to capture the value in the key variable in order to feed that into the code that will convert the encrypted version back into the original. This version creates a hexadecimal string as its output. To obtain an ASCII string instead we simply substitute the byteArrayToString() function for byteArrayToHex() in the last line.
To be able to convert the encrypted string back into readable text we need to reverse the process. To do this we need to input both the encrypted text and that key value into the following code.
var decryptedtext = byteArrayToString(
rijndaelDecrypt(hexToByteArray(ciphertext), key, mode));
Again, if the encrypted value is an ASCII string instead of hexadecimal we substitute stringToByteArray() for hexToByteArray() in the code.
This article written by Stephen Chapman, Felgall Pty Ltd.