- 仿射密码
仿射密码的映射函数为f(ai)=bi=aj,j=ik1+k0 mod n ,(k1,n)=0,0<k0<n,且不容许同时有k1=1和k0=0。
#仿射密码------------------------------------------------------------------------------------------------------
def judge(a,b): #判断两个数是否互质
temp = 0
while(b != 0):
temp = b;
b = a % b
a = temp
if(a == 1):
return True
else:
return False
dic = {}
A = ord('A')
for i in range(26): #构造一个{"0":"A",......,"25":"Z"}的字典
dic[i] = chr(A+i)
while(True): #控制合法输入
k1 = int(input("请输入一个与26互素的正整数k1:"))
k2 = int(input("请输入一个正整数k2:"))
if(judge(k1,26)):
if(k1 == 1 and k2 == 0):
print("您输入的k2不符合要求,请按要求重新输入。")
else:
break;
else:
print("您输入的k1不符合要求,请按要求重新输入。")
a = input("请输入明文:\n")
mingwen = []
mingwen.extend(a)
len = len(mingwen)
print("仿射密码机密后的密文为:")
for i in range(len): #循环拿一个明文字符与字典value匹配
if(mingwen[i] == ' '):
print(' ',end = '')
else:
temp = mingwen[i]
for key,value in dic.items():
if temp == value: #找到明文字符对应的key
x = (key * k1 + k2)%26
print(dic[x],end = '')
print('\n',end = '')
结果如图:
- 维吉尼亚密码
对照表:
#维吉尼亚密码-----------------------------------------------------------------------------------------------
dic = {}
A = ord('A')
for i in range(26): #构造一个{"0":"A",......,"25":"Z"}的字典
dic[i] = chr(A+i)
def find(miy): #找到密钥对应的key值
#dic = {}
#A = ord('A')
#for i in range(26): #构造一个{"0":"A",......,"25":"Z"}的字典
# dic[i] = chr(A+i)
list = []
for i in range(len(miy)): #循环拿一个密钥字符与字典value匹配
if(miy[i] == ' '):
print('',end = '')
else:
temp = miy[i]
for key,value in dic.items():
if temp == value: #找到密钥字符对应的key
list.append(key)
return list #返回处理后的密钥对应的key值列表
a = input("请输入明文:\n")
mingwen = []
mingwen.extend(a)
b = input("请输入密钥:\n")
miy = []
miy.extend(b)
list = find(miy)
k = 0
print("维吉尼亚密码加密后的密文为:")
for i in range(len(mingwen)): #循环拿一个密钥字符与字典value匹配
if(mingwen[i] == ' '):
print(' ',end = '')
else:
temp = mingwen[i]
for key,value in dic.items():
if temp == value: #找到密钥字符对应的key
print(dic[(key+list[k])%26],end = '')
k = (k+1)%len(list)
print('\n',end = '')
结果如图:
- 沃南密码
a) Vernam密码的明文、密文和密钥均用二元数字序列表示。
b) 设明文M=(m0,m1,…,mn-1),密钥K=(k0,k1,…,kn-1),密文C=(c0,c1,…,cn-1),其中mi,ki,ci属于GF(2),则 ci=mi⊕ki,i=0,…,n-1
#Vernam密码(沃南密码)----------------------------------------------------------------------------------------
dic = {}
list = [1,0,0,0,0,0,0]
flag = 1 #进位标志
for i in range(26):
for j in [6,5,4,3,2,1,0]:
if flag == 1:
list[j] = (list[j]+flag)%2
if list[j]+flag == 2:
flag = 0
else:
list[j] = (list[j])%2
#dic[chr(ord('A')+i)] = list #错误(此处赋值的是指针,不是内容,需要用深拷贝)浪费将近俩小时!!!!
dic[chr(ord('A')+i)] = list[:] #正解
flag = 1
a = input("请输入明文:\n")
mingwen = []
mingwen.extend(a)
b = input("请输入密钥:\n")
miy = []
miy.extend(b)
k = 0
for temp in mingwen: #明文与密钥按位亦或
xa = dic[temp]
xb = dic[miy[k]]
k = (k+1)%len(miy)
for i in range(7):
if xa[i] == xb[i]:
print('0',end = '')
else:
print('1',end = '')
print(' ',end = '')
结果如图:
这是来自M大佬实现沃南密码的代码(这才叫python,疯狂膜拜):
m = input('请输入明文:')
s = input('请输入密钥:')
print('加密后的结果为:')
rlt = []
for i in range(len(m)):
n = bin(ord(m[i])^ord(s[i]))[2:]
rlt.append((7-len(n))*'0'+n)
print(' '.join(rlt))
效果当然不用说: