python 实现 移位密码

实现古典密码中的移位密码。要求用户自己输入明文密钥等参数实现移位密码的加解密,并恢复以下用移位密码加密的密文片段:

zvtlvmbznlakpwwlkpumshazvtlpuzhapuzvtlpunsvzzibalclyfvujlpuhdopslfvbmpukzvtlvuldovpzpypklzjluahukdolufvbkvuvaopundpsslclyjvtwhyl

所对应的明文和密钥。

解决方案如下:

❶设计思路

1. 加密函数,根据用户输入的明文密钥等实现移位密码的加密

2. 解密函数,根据密文和偏移量实现移位密码的解密

3. 主函数

用户输入明文和密钥

加密函数

用户输入待解密的密文

 解密函数

4. 恢复所给默认密文片段

❷实验内容和代码

2abb28cfc53a4efca540288aea934691.png

def shiftEncrypt(plaintext, key):
    ciphertext = ""
    for c in plaintext:
        if c.isalpha():
            if c.isupper():
                ciphertext += chr((ord(c) - 65 + key) % 26 + 65)
            else:
                ciphertext += chr((ord(c) - 97 + key) % 26 + 97)
        else:
            ciphertext += c
    return ciphertext

def shiftDecrypt(ciphertext, key):
    plaintext = ""
    for c in ciphertext:
        if c.isalpha():
            if c.isupper():
                plaintext += chr((ord(c) - 65 - key) % 26 + 65)
            else:
                plaintext += chr((ord(c) - 97 - key) % 26 + 97)
        else:
            plaintext += c
    return plaintext

def recoverPlaintext(ciphertext):
    for key in range(26):
        decrypted_text = shiftDecrypt(ciphertext, key)
        print(f"使用密钥{key}解密后的明文为:{decrypted_text}")


if __name__ == "__main__":

    plaintext = input("请输入明文")
    key = int(input("请输入密钥"))
    print(shiftEncrypt(plaintext,key))
    ciphertext = input("请输入密文")
    key = int(input("请输入偏移量"))
    print(shiftDecrypt(ciphertext,key))
    print("示例解密")
    input()
    ciphertext = ("zvtlvmbznlakpwwlkpumshazvtlpuzhapuzvtlp"
                  "unsvzzibalclyfvujlpuhdopslfvbmpukzvtlvu"
                  "ldovpzpypklzjluahukdolufvbkvuvaopundpss"
                  "lclyjvtwhyl")
    recoverPlaintext(ciphertext)

❸实验结果

cb2324e5bd4445b5a7dc7f134e8a216a.png

❹本题中遇到的问题及解决过程

问题

情况分析不全面,代码不容错,比如明文输入数字等情况

解决

加一些判断和容错,数字不进行位移

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值