RC4 is a stream cipher with symmetric keys. It was originally designed by Rivest for RSA Data Security (now RSA Security). On September 9, 1994, the RC4 algorithm was anonymously posted on the Internet on the Cyperpunks "anonymous remailers" list.
Why implementing it?
I implemented it for doing encryption in some of my small Java projects.
In Java, the "official" way to do encryption is to use the Java Cryptography Extension (JCE). JCE is available as a separate package for JDK 1.2 and 1.3. It is now integrated into JDK 1.4. However, JCE is too heavy for some of my projects. All I need is a simple class that can do RC4 encryption and decryption, without complicated key generation and agreement etc.
However, if you need encryption for a "real" application, I strongly recommend you to use JCE. Also, Cryptix is a free implementation of JCE that worth a try.
You can download my implementation of RC4 here. The package also includes a testing class for comparing result and speed between my implementation and Cryptix.
You can freely use the code and class for private and non-commercial purposes.
The Javadoc is available here.
The RC4 algorithm is actually quite simple. So I implemented it in a single class.
To do encryption or decryption, you need to create an instance of the RC4 class with the key first. Usually, key length is between 1 to 2048 bits. But my implementation doesn't check that.
String key = "12345"; RC4 rc4 = new RC4(key);
To do encryption/decryption, just pass the plain text/cipher text to the rc4 method:
byte result = rc4.rc4(data);
On my Duron 856 (107 * 8) with JDK 1.4.1_01 HotSpot Server VM, my implementation can perform at around 15.6MB/s.
With JDK 1.3.1_02 HotSpot Server VM, the speed is around 13MB/s.
I also include a Test class in the package. It is for testing and benchmarking only and is not required for RC4 encryption. The test compares the encryption result of random data and key between Cryptix's and my implementation.
To run the test, you need to have Cryptix installed and configured. For using Cryptix under JDK 1.4, remember to install the "Unlimited Strength" Jurisdiction Policy Files