LFSR python实现
作者:互联网
一.LFSR部分(线性反馈移位寄存器)
LFSR的优点:
a.非常适合硬件实现
b.能产生大的周期序列
c.能产生好的统计特性的序列
d.能应用代数方法进行分析
实现思路:
a是n个寄存器(状态)
c是种子密钥,对应着a的系数
输出是a1&cn
迭代方程为:
ai(t+1)=ai+1(t)(i=1,2,…,n-1)
an(t+1)=Σ(ci*an-i(t))
class LFSR():
def __init__(self, c=None, a=None, lenc=0): #c是开关(系数),a是初始状态
if a is None:
a = []
if c is None:
c = []
self.a = a
self.c = c
self.lenc = lenc
lena = len(a)
#如果lena比lenc短,那么将其拓展
def LeftShift(self):
lastb = 0
lenc = self.lenc
for i in range(lenc):
lastb = lastb ^ (self.a[i] & self.c[i])
b = self.a[1:]
b.append(lastb)
outp = self.a[0]
#体现linear
self.a = b
return outp
二.j-k触发器
j-k触发器有两个输入,对应着两个LFSR生成的序列输出
JK触发器的输出方程: ck = ak ^ (~(ak ^ bk) & ck-1)
class cypto_LFSR():
def __init__(self, key, lfsr1 = None, lfsr2 = None):
if lfsr1 is None:
lfsr1 = [0, 1, 0, 1]
if lfsr2 is None:
lfsr2 = [0, 0, 1, 1]
Keymap = key
lenk = len(Keymap)
self.lfsr1 = LFSR(Keymap, lfsr1, lenk)
self.lfsr2 = LFSR(Keymap, lfsr2, lenk) #生成LFSR伪随机序列
self.Key = Keymap
self.lc = 0
def GetBit(self):
ak = self.lfsr1.LeftShift()
bk = self.lfsr2.LeftShift()
ck = ak ^ (~(ak ^ bk) & self.lc) # JK触发器
self.lc = ck
return int(ck)
def do_crypt(self, LFSR_msg):
text = []
for i in LFSR_msg:
j, cnt = i, 8
tmp = []
while cnt > 0:
tmp.append(self.GetBit() ^ (j & 1))#低位放在了前面
j = j >> 1
cnt = cnt - 1
res = 0
for iti in range(7, -1, - 1):#按照[7,6,5,4,3,2,1]的顺序
res = res << 1
res = res + tmp[iti]
text.append(res)
return bytes(text)
三.完整代码
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 21 10:41:08 2020
@author: 15061
"""
import base64
def get_str_bits( s:str):
list_b = []
for i in s:
list_b.append((ord(i) - ord('0')))
return list_b
class LFSR():
def __init__(self, c=None, a=None, lenc=0): #c是开关(系数),a是初始状态
if a is None:
a = []
if c is None:
c = []
self.a = a
self.c = c
self.lenc = lenc
lena = len(a)
#如果lena比lenc短,那么将其拓展
def LeftShift(self):
lastb = 0
lenc = self.lenc
for i in range(lenc):
lastb = lastb ^ (self.a[i] & self.c[i])
b = self.a[1:]
b.append(lastb)
outp = self.a[0]
#体现linear
self.a = b
return outp
class cypto_LFSR():
def __init__(self, key, lfsr1 = None, lfsr2 = None):
if lfsr1 is None:
lfsr1 = [0, 1, 0, 1]
if lfsr2 is None:
lfsr2 = [0, 0, 1, 1]
Keymap = key
lenk = len(Keymap)
self.lfsr1 = LFSR(Keymap, lfsr1, lenk)
self.lfsr2 = LFSR(Keymap, lfsr2, lenk) #生成LFSR伪随机序列
self.Key = Keymap
self.lc = 0
def GetBit(self):
ak = self.lfsr1.LeftShift()
bk = self.lfsr2.LeftShift()
ck = ak ^ (~(ak ^ bk) & self.lc) # JK触发器
self.lc = ck
return int(ck)
def do_crypt(self, LFSR_msg):
text = []
for i in LFSR_msg:
j, cnt = i, 8
tmp = []
while cnt > 0:
tmp.append(self.GetBit() ^ (j & 1))#低位放在了前面
j = j >> 1
cnt = cnt - 1
res = 0
for iti in range(7, -1, - 1):#按照[7,6,5,4,3,2,1]的顺序
res = res << 1
res = res + tmp[iti]
text.append(res)
return bytes(text)
s="i_love_hnu"
k="1001"
key=get_str_bits(k)
l=cypto_LFSR(key)
print(l.do_crypt(get_str_bits(s)))
标签:lenc,None,python,LFSR,self,lfsr2,实现,lfsr1 来源: https://blog.csdn.net/qq_44109982/article/details/111488199