rc4加密解密算法python
时间: 2023-11-17 13:01:49 浏览: 53
以下是RC4加密解密算法的Python实现方法:
```python
class RC4:
def __init__(self, key):
self.key = key
def KSA(self):
keylength = len(self.key)
# Initialization
S = list(range(256))
j = 0
for i in range(256):
j = (j + S[i] + self.key[i % keylength]) % 256
S[i], S[j] = S[j], S[i] # Swap
return S
def PRGA(self, S):
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 encrypt(self, plaintext):
S = self.KSA()
keystream = self.PRGA(S)
res = []
for c in plaintext:
val = ("%02X" % (c ^ next(keystream))) # XOR and taking hex
res.append(val)
return ''.join(res)
def decrypt(self, ciphertext):
return bytes.fromhex(self.encrypt(bytes.fromhex(ciphertext))).decode('utf-8')
```
其中,RC4类包含了初始化函数KSA和伪随机生成算法PRGA,以及加密和解密函数encrypt和decrypt。在使用时,只需要创建一个RC4对象并传入密钥,然后调用encrypt和decrypt函数即可。