[python]自定义RC4算法
程序员文章站
2022-03-05 12:41:53
...
RC4算法的介绍
RC4算法是一种流加密算法。所谓流加密,即密文由明文与**逐比特异或所得。因此该算法仅包含初始化**生成算法(KSA算法)和伪随机**流生成算法(PRGA)。关于这两个算法的描述:
KSA算法
执行该算法需给定一个初始**key,key的长度可变(范围为1~256字节)。利用这个初始**,可以生成一个S盒(一般为256进256出)。
PRGA算法
执行该算法可以输出一个**流。假设明文长度为n,则该算法执行n次,将这n个**流与明文逐比特异或,即可得到密文。
语言:python
版本:3.7
#测试用例参考文件:'RC4 Encryption.pdf'
class RC4:
def __init__(self):
# 状态初始化
self.i = 0
self.n = 0
self.state = []
self.max_key_length = 256
def set_key(self, userkey=""):
for i in range(self.max_key_length):
self.state.append(i)
key_length = len(userkey)
T = []
userkey_bytes = userkey.encode()
for i in range(self.max_key_length):
elem = userkey_bytes[i % key_length]
T.append(elem)
j = 0
for i in range(self.max_key_length):
j = (j + T[i] + self.state[i]) % self.max_key_length
# 交换下标i和下标j对应的值
temp = self.state[i]
self.state[i] = self.state[j]
self.state[j] = temp
def keystream(self):
self.i = (self.i + 1) % self.max_key_length
self.n = (self.n + self.state[self.i]) % self.max_key_length
# 交换下标i和下标n的值
temp = self.state[self.i]
self.state[self.i] = self.state[self.n]
self.state[self.n] = temp
index = (self.state[self.i] + self.state[self.n]) % self.max_key_length
return self.state[index]
@staticmethod
def list2hex(list=[]):
result = ""
for elem in list:
result += str(hex(elem)[2:]).upper()
return result
@staticmethod
def list2str(list=[]):
result = ""
for elem in list:
result += str(chr(elem))
return result
def encrypt(self, message="", message2=[]):
if message:
msg_len = len(message)
message_bytes = message.encode(encoding='UTF-8', errors='strict')
elif message2:
msg_len = len(message2)
message_bytes = message2
cipher = []
for i in range(msg_len):
c = self.keystream() ^ message_bytes[i]
cipher.append(c)
return cipher
def decrypt(self, cipher=[]):
return self.encrypt("", cipher)
if __name__ == '__main__':
userkey = 'pwd12'
print("userkey(0x):")
print(userkey)
#userkey = userkey.decode()
rc4_enc = RC4()
rc4_dec = RC4()
rc4_enc.set_key(userkey)
rc4_dec.set_key(userkey)
# for i in range(16):
# print(hex(rc4.keystream()))
plain = "Math 310 Proves!"
cipher = rc4_enc.encrypt(plain)
print("\ncipher:")
print(rc4_enc.list2hex(cipher))
plain_new = rc4_dec.decrypt(cipher)
print("\nplain_new:")
print(rc4_dec.list2str(plain_new))
上一篇: lucene常用搜索排序摘录
下一篇: 关于lucene问题请进