仿射密码加解密代码python语言和运行操作,解密有问题

# 定义加密函数
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('输入错误,请重新输入!')

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值