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

ASCII+字符串移位加密程序:解密暴力枚举未还原原输入排查

问题排查与优化方案

问题原因分析

你的解密模块无法还原原输入,核心问题集中在以下几点:

  • ASCII移位逆操作逻辑完全错误:加密时是给字符ASCII码加偏移量,解密时应减去偏移量,但原代码中反而给ASCII码加0-25的偏移,方向完全相反。
  • 加密阶段ASCII移位未限制范围:原asciiShift直接将ASCII码加偏移,会生成非大写字母字符(如Z+1得到[),导致解密后无法还原为有效字母。
  • 字符串移位处理冗余混乱:原解密代码重复拼接字符串,枚举所有移位后未单独处理结果,输出大量无效内容,难以定位正确结果。

优化后的完整代码

def asciiShift(character, aShift):
    # 限制结果在大写字母ASCII范围内,避免生成特殊字符
    base = ord('A')
    offset = (ord(character) - base + int(aShift) % 26) % 26
    return base + offset

def stringShift(string, shift):
    # 用切片简化循环移位逻辑,等价于原逻辑但更高效
    shift = int(shift) % len(string)
    return string[shift:] + string[:shift]

def encrypt(message, aShift, sShift):
    # 统一转为大写处理
    upper_msg = message.upper()
    # 执行ASCII移位
    shifted_chars = [chr(asciiShift(c, aShift)) for c in upper_msg]
    shifted_str = ''.join(shifted_chars)
    # 执行字符串循环移位
    encrypted_str = stringShift(shifted_str, sShift)
    print(f"加密结果:{encrypted_str}")

def decrypt(message):
    msg_len = len(message)
    if msg_len == 0:
        print("空消息无法解密")
        return
    # 枚举所有可能的字符串移位偏移(0到消息长度-1)
    for s_shift_candidate in range(msg_len):
        # 还原字符串移位:加密时是左移sShift,解密时右移sShift等价于左移(msg_len - sShift%msg_len)
        shifted_back = ''
        for k in range(msg_len):
            idx = (k - s_shift_candidate) % msg_len
            shifted_back += message[idx]
        # 枚举所有可能的ASCII移位偏移(0到25)
        for a_shift_candidate in range(26):
            decrypted = []
            valid = True
            for char in shifted_back:
                # 只处理大写字母(加密阶段已保证输出为大写)
                if not ('A' <= char <= 'Z'):
                    valid = False
                    break
                base = ord('A')
                # 逆ASCII移位:减去偏移量后模26保证在字母范围内
                offset = (ord(char) - base - a_shift_candidate) % 26
                decrypted.append(chr(base + offset))
            if valid:
                print(f"字符串偏移{s_shift_candidate} | ASCII偏移{a_shift_candidate}: {''.join(decrypted)}")

# 主逻辑
typeConfirm = input("Encrypt or Decrypt? (E/D): ").strip().upper()
if typeConfirm.startswith('D'):
    decrypt_msg = input("输入加密消息: ").strip()
    decrypt(decrypt_msg)
elif typeConfirm.startswith('E'):
    message = input("输入原消息: ").strip()
    aShift = input("输入ASCII偏移量: ").strip()
    sShift = input("输入字符串偏移量: ").strip()
    
    # 检查无效字符
    invalid_chars = {'~', '{', '}'}
    for char in message:
        if char in invalid_chars:
            print("抱歉,加密器不支持以下特殊字符:~、{、},请更换后重试。")
            exit()
    encrypt(message, aShift, sShift)
else:
    print("输入错误,请输入E或D,程序退出...")
    exit()

关键修改说明

  1. 修复ASCII移位逻辑:
    • 加密时通过(ord(c)-ord('A') + 偏移) %26 + ord('A')保证结果始终是大写字母,避免生成特殊字符。
    • 解密时通过(ord(c)-ord('A') - 偏移) %26 + ord('A')执行逆操作,还原原字符。
  2. 简化字符串移位:用Python切片替代循环拼接,逻辑更清晰且高效。
  3. 优化解密枚举:
    • 分别枚举字符串移位和ASCII移位的所有可能组合,每个组合输出明确的标注,方便定位正确结果。
    • 增加有效性检查,跳过包含非大写字母的无效结果。
  4. 简化特殊字符检查:用集合存储无效字符,循环检查更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:36:29