实验目的及要求
(1)实现LFSR,寄存器位数n=10,反馈函数、初试值都自己定;
(2)实现RC4,数组长度=8,密钥自己定;
(3)基于实现的LFSR或RC4实现一个动态验证码生成器,每次生成6个伪随机十进制数,自己测下多少个输出后开始循环。
========================================================================================================================================================
(1)
def LFSR(register): output = register[0] # 输出最低有效位 feedback = register[0] ^ register[1] # 第一位和第二位异或 for i in range(len(register)-1): register[i] = register[i+1] # 左移寄存器的值 register[-1] = feedback # 拼接反馈位 return output, register # 初始化寄存器和反馈位tap origin=[1,0,0,0,1,1,0,1,1,1] register = [1,0,0,0,1,1,0,1,1,1] flag=0 while True: output, register = LFSR(register) print("输出:"+str(output)+" "+"左移后状态:"+str(register)) if register == origin: break else: flag+=1 print("周期是:"+str(flag))
以下是运行结果
输入的初始值不同,运行结果也不一样,有些会一直循环下去
========================================================================================================================================================
(2)
key = "helloworld" # 密钥 S = [0, 1, 2, 3, 4, 5, 6, 7] # 初始S盒 T = [] # 初始化T盒为空 j = 0 # j变量初始化为0 # 初始化S盒 for i in range(8): # 循环8次,与密钥长度相同 j = (j + S[i] + ord(key[i])) % 8 # j加S[i]值与密钥字符的ASCII值,取模8 S[i], S[j] = S[j], S[i] # 交换S[i]和S[j]的值 i=0 # i变量初始化为0 j = 0 # j变量重新初始化为0 # PRGA生成伪随机数 for _ in range(8): # 循环8次,与明文长度相同 i=(i+1)%8 # i加1,取模8 j = (j + S[i]) % 8 # j加S[i]值,取模8 S[i],S[j]=S[j],S[i] # 交换S[i]和S[j]的值 t=(S[i]+S[j])%8 # t取S[i]和S[j]之和的模8 T.append(S[t]) # 将S[t]的值添加到T盒 plaintext='woaimimadsa' # 明文 cypher=[] # 初始化密文为空 for i in range(8): # 遍历T盒的值 cypher.append(chr(ord(plaintext[i])^T[i])) # 明文的第i个字符与T[i]作异或,得密文的第i个字符 print("明文是:"+plaintext) print("密钥是:"+key) print("密文是:"+''.join(cypher)) # 输出密文
以下是运行结果
========================================================================================================================================================
(3)
key = 'helloworld' # 密钥 S = list(range(256)) # 初始S盒,值从0到255 j = 0 # j变量初始化为0 # 初始化S盒 for i in range(256): # 从0到255循环 j = (j + S[i] + ord(key[i % len(key)])) % 256 # j加S[i]值与密钥字符的ASCII值,取模256 S[i], S[j] = S[j], S[i] # 交换S[i]和S[j]的值 # 生成6位数验证码 def get_code(): code = [] # 初始化验证码为空列表 i, j = 0, 0 # i和j变量初始化为0 for _ in range(6): # 循环6次 i = (i + 1) % 256 # i加1,取模256 j = (j + S[i]) % 256 # j加S[i]值,取模256 S[i], S[j] = S[j], S[i] # 交换S[i]和S[j]的值 code.append(str(S[(S[i] + S[j]) % 256] % 10)) # 将S[i]和S[j]之和模256且模10的结果添加到验证码中 return ''.join(code) # 返回生成的6位数验证码 # 测试 n = 0 # 循环次数初始化为0 codes = set() # 初始化代码集合为空 while True: # 一直接循环 code = get_code() # 获取新的验证码 print(code,end=' ') if code in codes: # 如果验证码已在集合codes中 print(f'\n开始重复!循环次数:{n},重复验证码为:{code}') # 输出开始重复的循环次数n break # 退出循环 codes.add(code) # 将新验证码添加到集合codes中 n += 1 # 循环次数加1
以下是运行结果
标签:初始化,code,register,验证码,实验,print,256,序列密码 From: https://www.cnblogs.com/gaifa-gafin/p/17451304.html