top of page
FOLLOW ME
  • Black Facebook Icon

RC4 Stream Cipher in Verilog

  • Writer: Ahmed Mohamed
    Ahmed Mohamed
  • Mar 2, 2018
  • 2 min read

RC4 is a stream cipher that is used for generating pseudorandom stream of bits (a keystream). this generated key is combined with the plain text using bit-wise xor to perform encryption or combined with the cipher text to perform decryption, therefore the same algorithm is used for both encryption and decryption.

The RC4 algorithm consists of two parts :

  1. Key-scheduling algorithm (KSA)

  2. Pseudo-random generation algorithm (PRGA)

1- Key scheduled :

The key-scheduling algorithm is used to initialize the permutation in the array "S". "keylength" is defined as the number of bytes in the key and can be in the range 1 ≤ keylength ≤ 256, typically between 5 and 16, corresponding to a key length of 40 – 128 bits. First, the array "S" is initialized to the identity permutation. S is then processed for 256 iterations in a similar way to the main PRGA, but also mixes in bytes of the key at the same time.


for i from 0 to 255

S[i] := i

endfor

j := 0

for i from 0 to 255

j := (j + S[i] + key[i mod keylength]) mod 256 swap values of S[i] and S[j]

endfor


2- Pseudo-random generation algorithm (PRGA) :

In each iteration, the PRGA increments i, looks up the ith element of S, S[i], and adds that to j, exchanges the values of S[i] and S[j], and then uses the sum S[i] + S[j] (modulo 256) as an index to fetch a third element of S, (the keystream value K below) which is bitwise exclusive OR'ed (XOR'ed) with the next byte of the message to produce the next byte of either ciphertext or plaintext. Each element of S is swapped with another element at least once every 256 iterations.


i := 0

j := 0

while GeneratingOutput:

i := (i + 1) mod 256

j := (j + S[i]) mod 256

swap values of S[i] and S[j]

K := S[(S[i] + S[j]) mod 256]

output K

endwhile





The initial key length is set to 256, this key is written in a text file and used to initialize Rom in Verilog


Key ROM :


A Ram is used for the storage of the generated key during the key schedual stage and the Pseudo-random generation stage

RAM :

Finally a control FSM is used to control the access of the key Rom and the key Ram to perform the key scheduale and the output generation


Controller :


RC4 Test bench


Simulation results :

Comments


Subscribe to get upcoming FPGA projects by email

SEARCH BY TAGS
FEATURED POSTS
bottom of page