解析Python RC4密码中的索引器

2024-04-25 07:18:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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

Tags: keyinnumpyforlendefnprange
1条回答
网友
1楼 · 发布于 2024-04-25 07:18:26

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

但我从你后来的评论中看到,你纠正了它

第二个错误是打字错误:您写的是paintext,而不是plaintext

因此,稍后您将尝试将字符串上的XOR计数为参数之一 (仍然包含“任务完成”)和第二个论点 是一个Numpy数组

相关问题 更多 >