Principle and Implementation of RC4 Encryption Algorithm

Source: Internet
Author: User
Tags ranges

RC4 proposed in 1987 that, like the DES algorithm, is a symmetric encryption algorithm, that is, the key used is a single key (or private key ). However, unlike des, RC4 does not group the plaintext, but encrypts each byte in the plaintext in sequence by byte streams. During decryption, each byte in the ciphertext is decrypted in sequence.

The RC4 algorithm features a simple algorithm, fast operation, and variable key length. The variable range is 1-bytes (8-bits, when the key length is 128 bits, it is not feasible to search for the key using the violence law. Therefore, we can predict that the range of the RC4 key can defend against the attack of the violent search key for a long time in the future. In fact, no effective attack method has been found for the RC4 encryption algorithm with-bit key length.

Before introducing the principles of the RC4 algorithm, let's take a look at several key variables in the algorithm:

1. cipher stream: the Key of the RC4 algorithm is to generate a corresponding cipher stream based on the plaintext and key. The length of the cipher stream corresponds to the length of the plaintext, that is, the length of the plaintext is 500 bytes, the encrypted stream is also 500 bytes. Of course, the ciphertext generated by encryption is also 500 bytes, because the ciphertext is I bytes = I bytes ^ I bytes of the dense stream;

2. State vector S: The length is 256, s [0], s [1]... s [255]. Each unit is a byte. At any time when the algorithm is running, S contains an arrangement and combination of 8 bits ranging from 0 to, except that the value position is changed;

3. Temporary vector T: The length is also 256, and each unit is also a byte. If the key length is 256 bytes, the key value is directly assigned to T. Otherwise, each byte of the key is rotated to T;

4. Key K: The length is 1-128 bytes. Note that the length of the key keylen is not necessarily related to the length of the plaintext and the length of the dense stream. Generally, the length of the key is 16 bytes (BITs ).


The principle of RC4 is divided into three steps:

1. initialize S and T

For I = 0 to 255 do

S [I] = I;

T [I] = K [imodkeylen];

2. Initial arrangement of S

J = 0;

For I = 0 to 255 do

J = (J + S [I] + T [I]) mod256;

Swap (s [I], s [J]);

3. Generate a dense stream

I, j = 0;

For r = 0 to Len do // R is the plain length, r bytes

I = (I + 1) mod 256;

J = (J + S [I]) mod 256;

Swap (s [I], s [J]);

T = (s [I] + s [J]) mod 256;

K [R] = s [T];


The following describes the C ++ Implementation of RC4 encryption and decryption:

Encryption Class:

/* Encryption Class */class RC4 {public:/* constructor. The parameter is the key length */RC4 (int kl): keylen (kL) {srand (unsigned) time (null); For (INT I = 0; I <kl; ++ I) {// random production of keylen-byte key int TMP = rand () % 256; K. push_back (char (TMP);}/* ciphertext generated by plaintext */void encryption (const string &, const string &, const string &); Private: unsigned char s [256]; // state vector, 256 bytes in total unsigned char T [256]; // temporary vector, 256 bytes in total int keylen; // key length, keylen byte, value range: 1-256 vector <char> K; // variable length key vector <char> K; // dense stream/* initialize state vector S and temporary vector t for the keystream method to call */void initial () {for (INT I = 0; I <256; ++ I) {s [I] = I; t [I] = K [I % keylen] ;}}/* Initial permutation state vector S, which is used by the keystream method to call */void ranges () {Int J = 0; For (INT I = 0; I <256; ++ I) {J = (J + S [I] + T [I]) % 256; // cout <"J =" <j <Endl; s [I] = s [I] + s [J]; s [J] = s [I]-s [J]; s [I] = s [I]-s [J] ;}/ * generate the dense stream Len: the plaintext is LEN byte */void keystream (INT Len) ;}; void RC4: keystream (INT Len) {initial (); ranges (); int I = 0, j = 0, T; while (Len --) {I = (I + 1) % 256; j = (J + S [I]) % 256; s [I] = s [I] + s [J]; s [J] = s [I]-s [J]; s [I] = s [I]-s [J]; t = (s [I] + s [J]) % 256; K. push_back (s [T]) ;}} void RC4: encryption (const string & plaintext, const string & KS, const string & ciphertext) {ifstream in; ofstream out, outks; in. open (plaintext); // get the length of the input stream in. seekg (0, IOS: End); int lenfile = in. tellg (); In. seekg (0, IOS: Beg); // produces the encrypted stream keystream (lenfile); outks. open (KS); For (INT I = 0; I <lenfile; ++ I) {outks <(K [I]);} outks. close (); // The plaintext content is read into bits. unsigned char * bits = new unsigned char [lenfile]; In. read (char *) bits, lenfile); In. close (); out. open (ciphertext); // The plaintext is in bytes different from the encrypted stream or is then output to the ciphertext file for (INT I = 0; I <lenfile; ++ I) {out <(unsigned char) (BITS [I] ^ K [I]);} <span style = "white-space: pre"> </span> out. close (); Delete [] bits ;}
Decryption class:

/* Decryption class */class rc4_decryption {public:/* constructor. The parameter is the encrypted stream file and the ciphertext file */rc4_decryption (const string KS, const string CT ): keystream (KS), ciphertext (CT) {}/* decryption method. The parameter is the decryption file name */void decryption (const string &); Private: String ciphertext, keystream ;}; void rc4_decryption: decryption (const string & res) {ifstream inks, INCP; ofstream out; inks. open (keystream); INCP. open (ciphertext); // calculate the ciphertext length of inks. seekg (0, IOS: End); const int lenfile = inks. tellg (); inks. seekg (0, IOS: Beg); // read the dense stream unsigned char * bitkey = new unsigned char [lenfile]; inks. read (char *) bitkey, lenfile); inks. close (); // read the ciphertext unsigned char * bitcip = new unsigned char [lenfile]; INCP. read (char *) bitcip, lenfile); INCP. close (); // The decryption result is output to the decryption file out. open (RES); For (INT I = 0; I <lenfile; ++ I) out <(unsigned char) (bitkey [I] ^ bitcip [I]); out. close ();}

During program implementation, it should be noted that the type of the State Vector Array s and the temporary Vector Array T should be set to unsigned char rather than char. In some machines, char is treated as signed Char by default. When I and j are calculated in the algorithm, char is converted to int. If it is signed Char, after the 8-bit copy of Char to the low 8-bit of int, the char symbol is used to add 0 or 1 to the high position of Int. Because the key is randomly generated, if a byte of the key is 1, the calculated array subscript is negative, and it will cross the border.


Program running example

Main function:

Int main () {RC4 RC4 (16); // The key length is 16 bytes rc4.encryption ("plaintext .txt", "cipher stream .txt", "cipher stream .txt"); rc4_decryption decrypt ("cipher stream .txt ", "cipher .txt"); decrypt. decryption ("Encryption File .txt ");}

Plaintext: I love bunny!

Ciphertext: 'hybrid L & T hybrid 6 continents

Dense stream: 3 Gbit/s u

File decryption: I love bunny!


This is the first blog on network security. If you have any mistakes, please correct me!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.