仿射密码是一种替换密码。它是一个字母对一个字母的。
它的加密函数是 Ek(x)=(k1x+k2) mod n(其中k1和n互质,n是字母的数目)
解码函数是 Dk(x)=ny(x- k2) mod n (其中ny代表逆元,满足(k1*ny) mod n = 1)
因为用到文件交互,所以需把密码文件和此算法放在同一文件夹中,或者修改代码里面的密码文件路径。
#仿射密码加密与解密实现算法
# -*- coding=utf-8 -*-
#输入密钥
def accept():
k1,k2 = map(int,input('请输入两个密钥(以空格隔开):').split())
while gcd(k1, 26) !=1:
k1,k2 = map(int,input('k1和26不互素,请重新输入密钥:').split())
return k1,k2
#判断互素
def gcd(k1,m):
t = 0
while m!=0:
t = m
m = k1%m
k1 = t
return k1
#求逆元
def niyuan(k1):
n = 1
while (k1 * n) % 26 != 1:
n += 1
return n
#加密算法
def encrypt():
#输入密钥
k1,k2 = accept()
f = open('plaintext.txt')
plain = f.read()
c = []
for i in range(len(plain)):
#小写字母
if plain[i].islower():
c.append(chr(((ord(plain[i])-97)*k1+k2)%26+97))
#大写字母
elif plain[i].isupper():
c.append(chr(((ord(plain[i])-65)*k1+k2)%26+65))
#其他
else :
c.append(plain[i])
cipher = ''.join(c)
w = open('ciphertext.txt','w')
w.write(cipher)
print('加密完成!')
f.close()
w.close()
#解密算法
def decrypt():
#输入密钥
k1,k2 = accept()
#逆元
ny = niyuan(k1)
f = open('ciphertext.txt')
cipher = f.read()
p = []
for i in range(len(cipher)):
#小写字母
if cipher[i].islower():
t1 = ord(cipher[i])-97-k2
if t1 < 0:
t1 +=26
p.append(chr((ny * t1)%26+97))
#大写字母
elif cipher[i].isupper():
t2 = ord(cipher[i])-65-k2
if t2 < 0:
t2 +=26
p.append(chr((ny * t2)%26+65))
#其他
else :
p.append(cipher[i])
plain = ''.join(p)
w = open('plaintext_new.txt','w')
w.write(plain)
print('解密完成!')
f.close()
w.close()
if __name__ == '__main__':
while True:
ch = int(input("加密请输入【1】:\n解密请输入【2】:\n退出请输入【3】:"))
if ch == 1:
encrypt()
elif ch == 2:
decrypt()
elif ch == 3:
exit()
else:
print("请输入1或2")