The RC4 encryption Algorithm (HTTP://EN.WIKIPEDIA.ORG/WIKI/RC4) is the top figure in the famous RSA trio Ron Rivest was designed in 1987 with a variable key-length stream cipher algorithm cluster. It is called a cluster, because its core part of the S-box length can be arbitrary, but generally 256 bytes. The speed of the algorithm can reach about 10 times times of DES encryption, and it has a high level of nonlinearity. RC4 was originally used to protect trade secrets. But in September 1994, its algorithms were posted on the Internet, and there was no more trade secrets. RC4 is also called ARC4 (alleged rc4--so-called RC4), because RSA has never formally published this algorithm.
The RC4 principle is very simple, including the initialization algorithm (Ksa/setkey) and pseudo-random codon generation algorithm (prga/transform) two parts. The implementation code is as follows (VS2008):
[CPP]View Plaincopy
- Rc4.h
- template<class t> inline void
- Swap (t& I, t& j)
- {
- T tmp = i;
- i = j;
- j = tmp;
- }
- Class RC4
- {
- Public
- void Setkey (const char* key, int keylen);
- void Transform (char* output, const char* input, int len);
- Private
- unsigned char key_[256];
- };
- /////////////////////////////////////////////
- rc4.cc
- #include "rc4.h"
- void Rc4::setkey (const char* key, int keylen)
- {
- For (int i = 0; i <; i++)
- {
- Key_[i] = i;
- }
- int j = 0;
- For (int i = 0; i <; i++)
- {
- j = (j + key_[i] + Key[i%keylen])% 256;
- Swap (Key_[i], key_[j]);
- }
- }
- void Rc4::transform (char* output, const char* input, int len)
- {
- int i = 0, j = 0;
- For (int k = 0; k < Len; k++)
- {
- i = (i + 1)% 256;
- j = (j + key_[i])% 256;
- Swap (Key_[i], key_[j]);
- unsigned char subkey = key_[(Key_[i] + key_[j])% 256];
- Output[k] = subkey ^ Input[k];
- }
- }
- /////////////////////////////////////////
- main.cc
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include "rc4.h"
- int main ()
- {
- char input[256] = "Times teaches all things to him who lives forever but I had not the luxury of eternity.";
- char output[256] = "";
- printf ("before encrypt:%s/n", input);
- const int keylen = 16;
- char Key[keylen] = "";
- For (int i = 0; i < Keylen; i++)
- {
- Key[i] = rand ()% 256;
- }
- RC4 Rc4encrypt, Rc4decrypt;
- Rc4encrypt. Setkey (key, Keylen);
- Rc4decrypt. Setkey (key, Keylen);
- Rc4encrypt. Transform (output, input, strlen (input));
- printf ("After encrypt:%s/n", output);
- Rc4decrypt. Transform (output, output, strlen (input));
- printf ("After decrypt:%s/n", output);
- return 0;
- }
RC4 encryption algorithm and its implementation