... Wheeler & Needham’s Tiny Encryption Algorithm is a simple but powerful encryption algorithm (based on a ‘Feistel cipher’).
This is a JavaScript implementation of the (corrected) ‘Block TEA ’ or ‘large block’ version of the algorithm (also dubbed ‘xxtea’) which operates on variable-sized blocks, as opposed to the 64-bit blocks of the original.
This is a simple but highly effective DES-style encryption algorithm which can be useful for web applications which require security or encryption. It provides very secure cryptographically strong encryption in concise, clear JavaScript code.
The Block TEA version is faster than the original (64-bit block version) when encrypting longer blocks (over 16 chars), and is more secure (‘a single bit change will change about one half of the bits of the entire block, leaving no place where the changes start’). It is also simpler to implement in JavaScript for encrypting arbitrary-length texts (being variable block size, it requires no ‘mode of operation’). For an implementation of the original algorithm, see tea.html.
TEA uses a 128-bit key, which could (for increased security) be an encrypted (or hashed) form of the supplied password. Here I simply convert the first 16 characters of the password into longs to generate the key. The password might be a user-supplied password, or an internal system password. A system password will be more secure if it avoids plain-text (e.g. ‘dVr4t%G§Uu+mz7+8’).
I needed to encrypt text, not binary data, so I have built on this so that it operates on text rather than just on numeric arrays, and also rearranged it slightly so that p is not referenced outside the for loop (valid in C, but not always in other languages). The ciphertext is encoded as Base64 so that it can be safely stored and/or transmitted without troublesome control characters causing problems. The plaintext is first converted to UTF-8 so that the script is multi-byte-character safe.
Speed: using IE on a 3GHz P4 the script processes around 80kB/sec (around 25 pages of text), though it slows down with longer texts.
...For an explanation of the operation of the TEA algorithm, and cryptography in general, an excellent book is Information Security Intelligence: Cryptographic Principles & Applications by Tom Calabrese (available from Amazon.com). There is also a good article explaining TEA operation and cryptanalysis by Matthew Russell from York University and a short article in Wikipedia.
Note: if you are interested in cryptanalysis of TEA, bear in mind that there are 4 versions described in 3 documents: the original TEA, then Extensions to TEA (addressing weaknesses in TEA and also describing Block TEA), and Corrections to Block TEA (aka xxtea). This page implements the last of these.
If you want industrial-strength encryption, I have also implemented a version of AES.
...