#####################仿射加密####################
letter_list="ABCDEFGHIJKLMNOPQRSTUVWXYZ" #字母表
#gcd函数,求最大公约数
def gcd(a,b):
if(a<b):
t=a
a=b
b=t
while(0!=b):
t=a
a=b
b=t%b
return a
#求逆元函数
def GetInverse(a,m):
for i in range(m):
if(1==(a*i)%m):
return i
#加密函数
def Encrypt(plaintext,key1,key2):
ciphertext=""
for ch in plaintext: #遍历明文
if ch.isalpha(): #明文是否为字母,如果是,则判断大小写,分别进行加密
if ch.isupper():
ciphertext+=letter_list[(key1*(ord(ch)-65)+key2) % 26]
else:
ciphertext+=letter_list[(key1*(ord(ch)-97)+key2) % 26].lower()
else: #如果密文不为字母,直接添加到密文字符串里
ciphertext+=ch
return ciphertext
#解密函数
def Decrypt(ciphertext,key1,key2):
plaintext=""
for ch in ciphertext: #遍历密文
if ch.isalpha(): #密文为否为字母,如果是,则判断大小写,分别进行解密
if ch.isupper():
plaintext+=letter_list[GetInverse(key1,26)*(ord(ch)-65-key2) % 26]
else:
plaintext+=letter_list[GetInverse(key1,26)*(ord(ch)-97-key2) % 26].lower()
else: #如果密文不为字母,直接添加到明文字符串里
plaintext+=ch
return plaintext
#主函数
print("加密请按D,解密请按E:")
user_input=input();
while(user_input!='D' and user_input!='E'):#输入合法性判断
print("输入有误! 请重新输入:")
user_input=input()
print("请输入两个密钥,且gcd(key1,26)==1:")
key1=input("key1:")
key2=input("key2:")
while(1): #输入合法性判断
if(0==int(key1.isdigit()) or 0==int(key2.isdigit())):
print("输入有误! 密钥为数字,请重新输入:")
key1=input("key1:")
key2=input("key2:")
elif(gcd(int(key1),26)!=1):
print("输入有误! key1和26必须互素,请重新输入:")
key1=input("key1:")
key2=input("key2:")
else:
break;
if user_input=='D':
#加密
print("请输入明文:")
plaintext=input()
ciphertext=Encrypt(plaintext,int(key1),int(key2))
print("密文为:\n%s" % ciphertext)
else:
#解密
print("请输入密文:")
ciphertext=input()
plaintext=Decrypt(ciphertext,int(key1),int(key2))
print("明文为:\n%s" % plaintext)
仿射加密
最新推荐文章于 2023-09-26 23:18:38 发布