def KSA(key): """Key Scheduling Algorithm (KSA)""" 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): """Pseudo-Random Generation Algorithm (PRGA)""" i = 0 j = 0 while True: i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j], S[i] # swap K = S[(S[i] + S[j]) % 256] yield K
def RC4(key, data): S = KSA(key) keystream = PRGA(S) return bytearray([c ^ next(keystream) for c in data])
# 解密函数 def rc4_decrypt(key, ciphertext): key = [ord(c) for c in key] # Convert key to list of integers ciphertext = bytearray.fromhex(ciphertext) # Convert ciphertext from hex to bytearray decrypted = RC4(key, ciphertext) return decrypted.decode('utf-8')