RC4 is a variable key-length stream encryption algorithm designed by Ron Rivest in 1987. It uses the same key for decryption, and therefore also belongs to the symmetric encryption algorithm. RC4 is a cryptographic algorithm used in Wired equivalent encryption (WEP) and is one of the algorithms that TLS can employ. Because of weaknesses in the RC4 algorithm, RFC 7465 stipulates that the use of the RC4 encryption algorithm in TLS is prohibited [1].
The RC4 consists of a pseudo-random number generator and an XOR operation. The key length of the RC4 is variable, and the range is [1,255]. RC4 a byte and a byte to decrypt. Given a key, the pseudo-random number generator accepts the key and produces an S-box. The S box is used to encrypt the data, and the S box changes during the encryption process.
Because of the RC4 of XOR operations, the same set of algorithms is used for encryption and decryption.
pseudo-random number generator:
Initialize the S box with a length of 256. The first for loop loads the non-repeating elements from 0 to 255 into the S box. The second for loop disrupts the s box according to the key.
defRc4_init (SBox, key, length):" "param1: A 256-length str array, param2: Key, can be arbitrarily defined, long param3: The length of the key," "I, J=0, 0 K= [0] * 256Temp=0 forIinchRange (256): Sbox[i]=I k[i]= key[i%Length] forIinchRange (256): J= (j + sbox[i] + k[i])%256Temp=Sbox[i] Sbox[i]=Sbox[j] Sbox[j]=Tempreturn
During initialization, the main function of the key is to disturb the s-box, I ensure that each element of the S-box is processed, and J guarantees that the S-box is randomly disturbed. The different s-box can get different sub-key sequences after the pseudo-random codon generation algorithm, and the XOR operation between S-box and plaintext is obtained, and the decryption process is identical.
defRc4_crypt (sBox, data, length):" "param1: Scrambled S-box param2: The length of the data param3:data that need to be encrypted" " forKinchRange (length): I= (i + 1)% 256J= (j + sbox[i])% 256Temp=Sbox[i] Sbox[i]= Sbox[j]#Exchange S[i] and S[j]SBOX[J] =Temp T= (S[i] + s[j])% 256Data[k]^= S[t]#and OR Operations return
This algorithm guarantees that each element of the S box in every 256 cycles is exchanged at least once.
Reference documents:
Wikipedia: Http://zh.wikipedia.org/wiki/RC4
RC4 Encryption algorithm