我正在尝试将 RC4 从 Python 转换为 Pascal。
这是工作的 Python 代码(不是我写的):
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]
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 = 'Secret'
plaintext = 'Attack at dawn'
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)
plaintext = np.array([ord(i) for i in plaintext])
cipher = keystream ^ plaintext # ^ is XOR
print(cipher.astype(np.uint8).data.hex())
print([chr(c) for c in cipher])
这是我的非工作 Pascal 代码:
program rc4;
uses
sysutils;
type
myArray = array[0..255] of integer;
var
S, keystream, cipher : myArray;
key, plaintext, cipherString : string;
i : integer;
function KSA(key : string) : myArray;
var
i, j, key_length, temp: integer;
begin
temp := 0;
key_length := length(key);
for i := 0 to 255 do
S[i] := i;
j := 0;
for i := 0 to 255 do
begin
j := (j + S[i] + ord(key[i mod key_length])) mod 256;
temp := s[i];
S[i] := S[j];
S[j] := temp;
end;
KSA := S;
end;
function PRGA(S : myArray ; n : integer) : myArray;
var
i, j, K, temp : integer;
key : myArray;
begin
i := 0;
j := 0;
K := 0;
temp := 0;
while n > 0 do
begin
n := n - 1;
i := (i + 1) mod 256;
j := (j + S[i]) mod 256;
temp := S[i];
S[i] := S[j];
S[j] := temp;
K := S[(S[i] + S[j]) mod 256];
key[i-1] := K;
end;
PRGA := key;
end;
我假设目前主要的错误是在 KSA 函数中,因为当我在 KSA 的末尾打印出 S 数组时,我在 python 和 pascal 之间得到了不同的结果。我也认为 PRGA 有问题,因为我最后得到了否定的答案。
青春有我
相关分类