# 定义加密函数
def encrypt(plain_text, key):
# 去除空格和标点符号,只保留字母
plain_text = plain_text.translate(str.maketrans('', '', string.punctuation + ' '))
# 将明文转换为小写字母
plain_text = plain_text.lower()
# 初始化密文
cipher_text = ''
# 遍历明文中的每个字符
for c in plain_text:
# 如果是字母,则进行加密
if c.isalpha():
# 将字母转换为数字(a对应0,b对应1,以此类推)
num = ord(c) - ord('a')
# 使用仿射密码加密算法进行加密,公式为:E(x) = (ax + b) mod 26
num = (key['a'] * num + key['b']) % 26
# 将加密后的数字转换为字母
cipher_text += chr(num + ord('A'))
else:
# 如果不是字母,则直接添加到密文中
cipher_text += c
# 返回密文
return cipher_text
# 检查密钥是否合法
def check_key(key):
# 判断 a 和 26 是否互质(即 gcd(a, 26)=1)
if math.gcd(key['a'], 26) != 1:
return False
else:
return True
# 主函数
if __name__ == '__main__':
while True:
# 提示用户输入操作编号
choice = input("请输入操作编号(0-退出,1-加密,2-解密):")
# 如果用户输入0,则退出程序
if choice == '0':
break
# 如果用户输入1,则进入加密模式
elif choice == '1':
# 提示用户输入与26互质的整数a和密钥参数b
a = int(input("请输入一个与26互质的整数:"))
while True:
if not check_key({'a': a}):
a = int(input("输入错误,请重新输入一个与26互质的整数:"))
else:
break
b = int(input('请输入密钥参数b(任意整数):'))
# 定义密钥
key = {'a': a, 'b': b}
# 提示用户输入明文并加密输出密文
plain_text = input('请输入明文:')
cipher_text = encrypt(plain_text, key)
print('密文为:', cipher_text.upper())
# 如果用户输入2,则进入解密模式
elif choice == '2':
# 提示用户输入与26互质的整数a和密钥参数b
a = int(input("请输入一个与26互质的整数:"))
while True:
if not check_key({'a': a}):
a = int(input("输入错误,请重新输入一个与26互质的整数:"))
else:
break
b = int(input('请输入密钥参数b(任意整数):'))
# 定义密钥
key = {'a': a, 'b': b}
# 提示用户输入密文并解密输出明文
cipher_text = input('请输入密文:')
plain_text = encrypt(cipher_text, {'a': key['a'], 'b': 26 - key['b'] % 26})
print('明文为:', plain_text.lower())
# 如果用户输入其他字符,则提示输入错误
else:
print('输入错误,请重新输入!')
仿射密码加解密代码python语言和运行操作,解密有问题
最新推荐文章于 2024-07-12 16:16:27 发布