m ="n"# 明文
a =list(m)# 将明文转换为列表形式
k1 =17# 密钥k1与26互素的数
k2 =9# 偏移量# 将明文字符串转化为Acsll码然后将0-a,25-z对应deftihuan(a, m):
temp =[]for i inrange(len(m)):if a[i].islower():
temp.append(ord(a[i])-97)else:
temp.append(ord(a[i])-65)return temp
# 加密函数defencryption(temp, m, k1, k2):
c =[]for i inrange(len(m)):
c.append(chr((temp[i]*k1+k2)%26+97))return c
temp = tihuan(a, m)
c = encryption(temp, m, k1, k2)
c1 =""for i inrange(len(m)):
c1 = c1+c[i]# 将列表转化为字符串print(c1)
维吉尼亚密码
import math
m ="appliedcryptosystem"# 明文
a =list(m)
k ="cipher"# 密钥
b =list(k)# 确定分组数iflen(m)>len(k):
x =len(m)//len(k)else:
x =0# Asclldeftihuan(a, m):
temp =[]for i inrange(len(m)):if a[i].islower():
temp.append(ord(a[i])-97)else:
temp.append(ord(a[i])-65)return temp
# 加密defencryption(tempm, tempk, x):
c =[]
z =0
n =len(k)if x ==0:# 如果组数为0for i inrange(len(z, n)):
c.append(chr((tempm[i]+tempk[i % n])%26+97))else:for i inrange(x):for j inrange(z, n):
c.append(chr((tempm[j]+tempk[j %len(k)])%26+97))
z = n
n +=len(k)# 我是sb能用常量不要用变量for d inrange(x*len(k),len(m)):
c.append(chr((tempm[d]+tempk[d %len(k)])%26+97))return c
tempm = tihuan(a, m)
tempk = tihuan(b, k)
c = encryption(tempm, tempk, x)
c1 =""for i inrange(len(m)):
c1 = c1+c[i]print(c1)
hill密码
import numpy as np
m ='se'# 明文
a = np.matrix([[11,2],[5,23]])# 密钥LCTFXZUHR
num_m =[]
temp =[]
count =1for i in m:# 将明文分为三个一组
temp.append(ord(i)-ord('A'))if count %3==0:
num_m.append(temp)
temp =[]
count +=1
mat_m =[np.matrix(i).T for i in num_m]# 将明文分组转换为向量形式
mat_c =[a * i %26for i in mat_m]# 得到密文分组的向量形式
num_c =[]
temp =[]for i in mat_c:# 将密文向量转换为列表形式,且合并到一个列表
temp = i.tolist()for j inrange(3):
num_c.append(temp[j][0])
c =[chr(i+ord('A'))for i in num_c]print(''.join(c))# 连接成字符串,输出密文