Resolving Indexerror In Python RC4 Cipher Code

160 Views Asked by At

I'm fairly new to programming in python and have been tasked with creating a RC4 cipher in python. This implementation utilizes numpy. If someone could help me resolve this error in the cipher code it'd be greatly appreciated.

RC4 Program

def KSA(key):
    key_length = len(key)
    S = list(range(256))
    j = 0
    for i in range(256):
        j = (j + S[i] + key[i % key_length]) % 256
        S[i], S[j] = S[j], S[i] #swap
    return S

def PRGA (S, n) :
    i = 0
    j = 0
    key =[]

    while n>0:
        n = n-1
        i = (i + 1) % 256
        j = (j + S[i]) % 256
        S[i], S[j] = S[j], S[i]
        K = S[(S[i]) + S[j] % 256]
        key.append(K)
    return key


key = 'KAREEM'
plaintext = 'Mission Accomplished'

def preparing_key_array(s):
    return [ord(c) for c in s]

key = preparing_key_array(key)

import numpy as np
S = KSA(key)

keystream = np.array(PRGA(S, len(plaintext)))
print(keystream)

paintext = np.array([ord(i) for i in plaintext])

cipher = keystream ^ plaintext #xor two numpy arrays

print ( cipher.astype(np.uint8).data.hex()) #print cipher codes
print ([chr(c) for c in cipher]) #print unicode

Output

================ RESTART: C:\Users\Admin\Desktop\Project\RC4.py ================
Traceback (most recent call last):
  File "C:\Users\Admin\Desktop\Project\RC4.py", line 36, in <module>
    keystream = np.array(PRGA(S, len(plaintext)))
  File "C:\Users\Admin\Desktop\Project\RC4.py", line 20, in PRGA
    K = S[(S[i]) + S[j] % 256]
IndexError: list index out of range
1

There are 1 best solutions below

0
Valdi_Bo On

The first error in your code was in line K = S[(S[i]) + S[j] % 256] in PRGA function.

But I see from your later comment that you corrected it.

The second error is a typo: you wrote paintext instead of plaintext.

So later you attempt to count XOR on a string as one of arguments (still containing 'Mission Accomplished') and the second argument is a Numpy array.