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

Vigenere Cipher仅单字符移位生效 多字符移位输出修复方案问询

Vigenere多字符移位问题修复方案

错误原因

现有代码存在三处核心逻辑错误,导致仅支持单字符处理:

  • 错误将密钥偏移列表、明文位置列表的元素直接拼接为大整数,完全违背Vigenere密码逐字符对应移位的设计逻辑,仅单字符场景下拼接后的值刚好等于原始偏移量,多字符场景下数值完全失效
  • 循环逻辑错误,使用拼接后的大整数作为循环次数,且加了break语句强制循环仅执行一次,永远只能输出单个字符
  • 未处理密钥与明文长度不匹配的场景,Vigenere密码要求密钥长度不足时循环重复匹配明文长度

修复步骤

  1. 完全删除将v1、v2列表转拼接大整数的冗余错误代码
  2. 新增密钥循环匹配逻辑,保证每一位明文字符都能对应到密钥偏移量
  3. 逐位遍历明文字符,依次计算对应偏移后的密文字符
  4. 统一输出最终加密结果

修复后可运行代码

def functions(decoded_list, keyword_list, ):
    shift_keyword_list = []
    position_decoded_list = []

    for letters in keyword_list:
        if letters in alpha:
            shift_keyword_list.append(alpha.index(letters) % 26)

    for letters in decoded_list:
        if letters in alpha:
            position_decoded_list.append(alpha.index(letters) % 26)

    return(shift_keyword_list, position_decoded_list)

alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

decoded = input("输入要加密的英文短语:")
decoded_list = list(decoded.upper())

keyword = input("输入加密密钥:")
keyword_list = list(keyword.upper())

v1, v2 = functions(decoded_list, keyword_list)  

encoded = ''
keyword_length = len(v1)
# 逐位计算密文
for index in range(len(v2)):
    current_shift = v1[index % keyword_length]
    current_plain_pos = v2[index]
    cipher_pos = (current_plain_pos + current_shift) % 26
    encoded += alpha[cipher_pos]

print("加密结果:", encoded.upper())

功能验证

输入明文HELLO、密钥ABC时,输出结果为HFNLP,符合Vigenere加密规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:15:03