A5/1 加密
这次是A5/1加密的学习过程,看了好多代码,感觉好多不同,对于密钥流的生成,有的是不定长的,有的又是定长的,而且有的只用Key不用帧序号,我这里是用了,初始化和前100步倒是正常,但这里报告要求的是先100次,再114次,取114的作为密钥流,然后再移动100次,再移动114次,取114次,最后组成228bit的KeyStream,然后密钥流是生成出来的,但也没有办法验证对不对,写了个测试,发现被加密的消息也要够长才好,不懂这个是不是硬性要求。希望有人能给个样例,在这里附上我的代码。import binascii
# 3个LFSR的初始状态全设为0
lr1 = * 19
lr2 = * 22
lr3 = * 23
# 移位函数
def shift(lst, value):
lst.pop()
lst.insert(0, value)
# 初始化阶段
def init_LR(key, fn):
for i in range(64):
x = key ^ lr1 ^ lr1 ^ lr1 ^ lr1
y = key ^ lr2 ^ lr2
z = key ^ lr3 ^ lr3 ^ lr3 ^ lr3
shift(lr1, x)
shift(lr2, y)
shift(lr3, z)
for i in range(22):
x = fn ^ lr1 ^ lr1 ^ lr1 ^ lr1
y = fn ^ lr2 ^ lr2
z = fn ^ lr3 ^ lr3 ^ lr3 ^ lr3
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, lr2, lr3)
if lr1 == m:
x = lr1 ^ lr1 ^ lr1 ^ lr1
shift(lr1, x)
if lr2 == m:
y = lr2 ^ lr2
shift(lr2, y)
if lr3 == m:
z = lr3 ^ lr3 ^ lr3 ^ lr3
shift(lr3, z)
# 生成密钥流
def generateKeyStream():
keyStream = []
for i in range(100):
shift_2()
for i in range(114):
shift_2()
keyStream.append(lr1 ^ lr2 ^ lr3)
for i in range(100):
shift_2()
for i in range(114):
shift_2()
keyStream.append(lr1 ^ lr2 ^ lr3)
return keyStream
# 字符串转2进制
def Str2Bin(string):
binary = bin(int(binascii.hexlify(string.encode()), 16))
return binary
# 二进制转16进制
def bin2hex(binary):
decimal = int(binary, 2)
hexadecimal = hex(decimal)
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) ^ keyStream)
print("加密:0x{}".format(bin2hex(cipher)))
#解密
m = ""
for i in range(len(message)):
m += str(int(cipher) ^ keyStream)
tmp = bin2hex(m)
print("解密:{}".format(hex2asc(tmp)))
页:
[1]