RC4(Rivest Cipher) is a stream cipher designed in 1987 by Ron Rivest. It is a variable key size with byte-oriented operations.
The important components of RC4 are:
cipher
.//Intialization
for i=0 to 255 do
S[i]=i;
T[i]=k[i mod keylen]
// Key Scheduling
j=0
for i=0 to 255 do
j=(j+S[i]+T[i]) mod 256;
swap(S[i] and S[j])
end for
// Pseudo-Random-Key-Generation
while(true)
i=i+1
j=(j+S[i])mod256;
swap(S[i]and S[j]);
t=(S[i]+S[j]) mod256;
key stream=S[t]
end for
[0,1,2,.....254,255]
totaling to 256-bytes in length.256
, the bytes key is assigned to T.S[0]
to S[255]
.S[i]
in the algorithm swaps it with another byte in S-array.
- Encryption -
(Plain Text)XOR(Keystream)
.- Decryption-
(CipherText)XOR(Keystream)
.
It is used in data communication and networking protocols.
RC4 is used in the Secure Sockets Layer/Transport Layer Security(SSL/TLS), which provides communication between Web browsers and users.
S=[0 1 2 3 4 5 6 7]
K=[1 2 3 6]
PT=[1 2 2 2]
T=[1 2 3 6 1 2 3 6]
j=(0+0+1) mod8=1
swap(S[0],S[1])
S=[1 0 2 3 4 5 6 7]
j=(1+0+2) mod8=3
swap(S[1],S[3])
S=[1 3 2 0 4 5 6 7]
j=(3+2+3) mod8=0
swap(S[2],S[0])
S=[2 3 1 0 4 5 6 7]
j=(0+0+6) mod8=6
swap(S[3],S[6])
S=[2 3 1 6 4 5 0 7]
j=(6+4+1) mod8=3
swap(S[4],S[3])
S=[2 3 1 4 6 5 0 7]
j=(3+5+2) mod8=2
swap(S[5],S[2])
S=[2 3 5 4 6 1 0 7]
j=(2+0+3) mod8=5
swap(S[6],S[5])
S=[2 3 5 4 6 0 1 7]
j=(5+7+6) mod8=2
swap(S[7],S[2])
S=[2 3 7 4 6 0 1 5]
Now finally the S is obtained
[2 3 7 4 6 0 1 5]
i=(0+1) mod 8=1
j=(0+3)mod 8=3
swap( S[1] ,S[3])
t=(4+3) mod 8=7
k=S(7)=5
S=[2 4 7 3 6 0 1 5]
i=(1+1) mod 8=2
j=(3+7)mod 8=2
swap( S[2] ,S[2])
t=(7+7) mod 8=6
k=S(6)=1
S=[2 4 7 3 6 0 1 5]
i=(2+1) mod 8=3
j=(2+3)mod 8=5
swap( S[3] ,S[2])
S=[2 4 7 0 6 3 1 5]
t=(0+3) mod 8=3
k=S(3)=0
S=[2 4 7 3 6 0 1 5]
i=(3+1) mod 8=4
j=(5+6)mod 8=3
swap( S[4] ,S[3])
S=[2 4 7 6 0 3 1 5]
t=(0+6) mod 8=6
k=S(6)=1
[5 1 0 1]
def KSA(key):S = list(range(256))j=0key_length=len(key)for i in range(256):j=(j+S[i]+key[i% key_length]) % 256S[i],S[j]= S[j],S[i]return Sdef PRGA(S,n):i=0j=0key=[]while n>0:n=n-1i=(i+1)%256j=(j+S[i])%256S[i],S[j]=S[j],S[i]K=S[(S[i]+S[j])% 256]key.append(K)return keykey ="Hello"PT= " MISSION ACCOMPLISHED"import numpy as npdef prep_key_array(s):return[ord(c)for c in s]key=prep_key_array(key)keystream=np.array(PRGA(KSA(key),len(PT)))print(keystream)