为了应付密码学作业而写的脚本

仿射变换

#C="YWPKXYHVKXONPTJCHYBXLPKTB"
#C="edsgickxhuklzveqzvkxwkzukvcuh"
M="cryptographyisthescienceandstudyofsecretwriting"
#M="THENATIONALSECURITYAGESNCY"
#String="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
String="abcdefghijklmnopqrstuvwxyz"
a=7
b=3
N=26
inv=15

def ennum(M,String):
    str_num=[]
    for m in M:
        i=0
        for n in String:
            if(m==n):
                print(m,':',i)
                str_num.append(i)
            i+=1
    return str_num

def denum(C_list):
    result=""
    for n in C_list:
        result+=String[n]

    return result

def encode(str_num,a,b,N):
    C_list=[]
    for i in range(0,len(str_num)):
        c=(str_num[i]*a+b)%N
        C_list.append(c)
    print("M:",M)
    print('Encode: ',denum(C_list))

def decode(str_num,a,b,inv,N):
    M_list=[]
    for i in range(0,len(str_num)):
        m=(inv*(str_num[i]-b+N))%N
        M_list.append(m)
    print("C:",C)
    print('Decode: ',denum(M_list))

def main():
    #C_str_num=ennum(C,String)
    M_str_num=ennum(M,String)
    #decode(C_str_num,a,b,inv,N)
    encode(M_str_num,a,b,N)

main()

扩展欧几里得算法

求逆元

a = int(input('请输入(a,b)中的a:'))
b = int(input('请输入(a,b)中的b:'))
print(a,' ',b)
if(a<=b):
    c = a
    a = b
    b = c

X1,X2,X3 = 1,0,a
Y1,Y2,Y3 = 0,1,b
print("%-5s" % "Q","%-5s" % "X1","%-5s" % "X2","%-5s" % "X3","%-5s" % "Y1","%-5s" % "Y2","%-5s" % "Y3")
print("%-5s" % "-","%-5s" % X1,"%-5s" % X2,"%-5s" % X3,"%-5s" % Y1,"%-5s" % Y2,"%-5s" % Y3)
while(1):
    q = X3//Y3
    T1,T2,T3 = (X1-Y1*q,X2-Y2*q, X3-Y3*q)
    X1,X2,X3 = Y1,Y2,Y3
    Y1,Y2,Y3 = T1,T2,T3
    print("%-5s" % q,"%-5s" % X1,"%-5s" % X2,"%-5s" % X3,"%-5s" %  Y1,"%-5s" % Y2,"%-5s" % Y3)
    if(Y3 == 1):
        print ("The inverse is:",Y2 % a)
        break
    elif(Y3 == 0):
        print('No inverse')
        break

线性反馈移位寄存器

import operator,copy
A_list=list(input('请输入A序列:'))
C_list=list(input('请输入C序列:'))

if(len(C_list) != len(A_list)):
    print('错误:A序列和C序列长度不一致')
def cal_An(t_list):
    O = []
    for i in range(0,len(t_list)-1):
        O.append(int(C_list[i]) * int(t_list[i]))
    An = O[0]
    for i in range(0,len(O)-1):
        On = An^O[i+1]
        An = On
    return str(An)

def exp():
    T_list = []
    M_list = []
    t_list = copy.copy(A_list)
    while(not operator.eq(T_list,A_list)):
        An = cal_An(t_list)
        t_list.append(An)
        M_list.append(t_list[0])
        T_list = copy.copy(t_list[1:])
        t_list = copy.copy(T_list)
        print(T_list)
    print('m序列为:',M_list)
    print('周期为:',len(M_list))

exp()

《为了应付密码学作业而写的脚本》有1条评论

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据