【发布时间】:2020-05-18 13:39:41
【问题描述】:
我对 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
【问题讨论】:
-
应该是
S[ ( (S[i]) + S[j] ) % 256]还是S[ (S[i]) + ( S[j] % 256 ) ]? (注意括号位置) -
我在更改括号@GPhilo 后收到了同样的错误
-
我的评论没有问它是否解决了问题(因为它没有),但你的索引的预期语义是什么。假设
S是 256 字节,我猜你试图做的是得到S[i]和S[j]和的模 256。但是,您的代码被严重括号括起来,因此您正在执行与我上面的第二个选项等效的操作,这可能会给您一个 >= 256 的数字,因此会出现 indexerror。 -
@GPhilo 是的,它的括号很严重。我通过将代码更改为
S[ (S[i] + S[j]) % 256 ]来纠正问题 -
太棒了,我通过转换密钥流和明文找到了答案。
cipher = keystream.astype(numpy.uint8) ^ plaintext.astype(numpy.uint8)
标签: python numpy encryption traceback rc4-cipher