You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python版维吉尼亚密码解密代码使其保留字母对应大小写

解决方案

问题根源是你调用casefold()将原始密文转为全小写后,完全丢失了原本的大小写信息,后续操作都是基于全小写字符串执行,自然无法还原正确的大小写格式。你需要保留原始密文的大小写标记,在生成解密字符时对应调整,同时你现有代码的偏移量计算逻辑存在错误,也会导致解密结果不符合预期。

修改思路

  • 单独存储全小写的密文副本用于解密计算,同时保留原始密文用于校验大小写
  • 修正偏移量判断逻辑:当计算得到的new_position < 0时需要加26取正,原逻辑判断条件写反
  • 得到解密后的小写字符后,判断原始密文对应位置的字符是否为大写,是则将解密字符转大写后再拼接

修正后完整代码

def decipher(key):    
    original = "Rpoe, Xknf cne Rosvuhcl"
    # 单独生成全小写的密文副本用于计算
    string_lower = original.casefold()
    Alphabet = "abcdefghijklmnopqrstuvwxyz"
    dec_message = ""
    key = key.lower()
    textlength = len(string_lower)
    exp_key = key
    exp_key_length = len(exp_key)
    # 扩展密钥长度匹配密文
    while exp_key_length < textlength:
        exp_key = exp_key + key
        exp_key_length = len(exp_key)
    key_position = 0
    # 同步遍历原始密文和小写密文副本
    for orig_char, lower_char in zip(original, string_lower):
        if lower_char in Alphabet:
            position = Alphabet.find(lower_char)
            key_char = exp_key[key_position]
            key_char_position = Alphabet.find(key_char)
            key_position += 1
            new_position = position - key_char_position
            # 修正偏移量调整逻辑
            if new_position < 0:
                new_position += 26
            new_character = Alphabet[new_position]
            # 匹配原始字符的大小写
            if orig_char.isupper():
                new_character = new_character.upper()
            dec_message += new_character
        else:
            dec_message += orig_char
    print(dec_message)
    print(original)
    return dec_message

decipher("ABC")

运行结果

调用函数后会输出正确的大小写匹配的解密结果:

Rome, Wine and Portugal
Rpoe, Xknf cne Rosvuhcl

内容的提问来源于stack exchange,提问作者Sebi Hanser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 02:39:00