解决Python RC4密码中的Indexerror

问题描述 投票:1回答:1

我对使用python编程还很陌生,并且受过在python中创建RC4密码的任务。此实现使用numpy。如果有人可以帮助我解决密码中的错误,将不胜感激。

RC4程序

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

输出

================ 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
python numpy encryption traceback rc4-cipher
1个回答
0
投票

您的代码中的第一个错误在第K = S[(S[i]) + S[j] % 256]行中在PRGA功能中。

但是我从您以后的评论中看到您已纠正它。

第二个错误是错字:您写了paintext而不是plaintext

因此,稍后您尝试将string上的XOR视为参数之一(仍包含'Mission Accomplished')和第二个参数是Numpy数组。

© www.soinside.com 2019 - 2024. All rights reserved.