[Python] 纯文本查看 复制代码
import binascii
# 3个LFSR的初始状态全设为0
lr1 = [0] * 19
lr2 = [0] * 22
lr3 = [0] * 23
# 移位函数
def shift(lst, value):
lst.pop()
lst.insert(0, value)
# 初始化阶段
def init_LR(key, fn):
for i in range(64):
x = key[i] ^ lr1[13] ^ lr1[16] ^ lr1[17] ^ lr1[18]
y = key[i] ^ lr2[20] ^ lr2[21]
z = key[i] ^ lr3[7] ^ lr3[20] ^ lr3[21] ^ lr3[22]
shift(lr1, x)
shift(lr2, y)
shift(lr3, z)
for i in range(22):
x = fn[i] ^ lr1[13] ^ lr1[16] ^ lr1[17] ^ lr1[18]
y = fn[i] ^ lr2[20] ^ lr2[21]
z = fn[i] ^ lr3[7] ^ lr3[20] ^ lr3[21] ^ lr3[22]
shift(lr1, x)
shift(lr2, y)
shift(lr3, z)
# 时钟函数
def maj(a ,b ,c):
if (a + b + c) >= 2:
return 1
else:
return 0
# 不规则阶段
def shift_2():
m = maj(lr1[8], lr2[10], lr3[10])
if lr1[8] == m:
x = lr1[13] ^ lr1[16] ^ lr1[17] ^ lr1[18]
shift(lr1, x)
if lr2[10] == m:
y = lr2[20] ^ lr2[21]
shift(lr2, y)
if lr3[10] == m:
z = lr3[7] ^ lr3[20] ^ lr3[21] ^ lr3[22]
shift(lr3, z)
# 生成密钥流
def generateKeyStream():
keyStream = []
for i in range(100):
shift_2()
for i in range(114):
shift_2()
keyStream.append(lr1[18] ^ lr2[21] ^ lr3[22])
for i in range(100):
shift_2()
for i in range(114):
shift_2()
keyStream.append(lr1[18] ^ lr2[21] ^ lr3[22])
return keyStream
# 字符串转2进制
def Str2Bin(string):
binary = bin(int(binascii.hexlify(string.encode()), 16))[2:]
return binary
# 二进制转16进制
def bin2hex(binary):
decimal = int(binary, 2)
hexadecimal = hex(decimal)[2:]
return hexadecimal
#16进制转ascii码
def hex2asc(hex_string):
bytes_obj = bytes.fromhex(hex_string)
ascii_string = bytes_obj.decode('ascii')
return ascii_string
key = [0, 1, 0, 0, 1, 1, 1, 0,
0, 0, 1, 0, 1, 1, 1, 1,
0, 1, 0, 0, 1, 1, 0, 1,
0, 1, 1, 1, 1, 1, 0, 0,
0, 0, 0, 1, 1, 1, 1, 0,
1, 0, 1, 1, 1, 0, 0, 0,
1, 0, 0, 0, 1, 0, 1, 1,
0, 0, 1, 1, 1, 0, 1, 0 ] #4E2F4D7C1EB88B3A
fn = [0, 1, 0, 0, 1, 1, 1, 0,
0, 0, 1, 0, 1, 1, 1, 1,
0, 1, 0, 0, 1, 1] #9C5E9
init_LR(key, fn)
keyStream = generateKeyStream()
#print(len(keyStream))
print("原文:hello,\nhex:0x68656c6c6fa")
message = Str2Bin("hello")
cipher = ""
#print(message)
#加密
for i in range(len(message)):
cipher += str(int(message[i]) ^ keyStream[i])
print("加密:0x{}".format(bin2hex(cipher)))
#解密
m = ""
for i in range(len(message)):
m += str(int(cipher[i]) ^ keyStream[i])
tmp = bin2hex(m)
print("解密:{}".format(hex2asc(tmp)))