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

Python流密码加解密代码终端运行异常,IDLE正常的问题求助

流密码加解密终端乱码问题排查与修复

问题根源

加密过程中,明文(比如空格、数字)经过%128运算后会生成不可打印的ASCII控制字符(例如空格的ASCII值为32,与密钥字符ASCII值相加取模128后,可能得到小于32的控制字符)。IDLE的输入框支持直接接收这类控制字符,但Windows/Linux终端的输入机制会过滤或转义此类字符,导致解密时输入的密文与加密生成的密文不一致,最终出现乱码。

修复方案

将加密后的二进制文本转换为Base64编码(全可打印字符),解密时先解码Base64再执行逆运算。这样无论在IDLE还是终端环境,都能正确传递加密内容。

修改后的完整代码:

import random
import urllib.request
import base64
from operator import add

word_site = "https://www.mit.edu/~ecprice/wordlist.10000"

class colours:
    RED = '\033[93m'
    WHITE = '\033[0m'
while True:
    print ('Type [e] to encrypt a message')
    print ('Type [d] to decrypt a message')
    print ('Type [q] to quit')

    select = input ('Selection: ')

    if select.lower() == 'q':
        quit()

    elif select.lower() == 'e':
        open_site = urllib.request.urlopen(word_site)
        words  = open_site.read().splitlines()

        while True:
            generate_key = str(random.choices([line for line in words],  k=1))
            key = (generate_key[3:-2])
            if len(key) > 5 and len(key) < 15:
                break
            else:
                continue

        msg = input ('Enter a message to be encrypted: ')
        keystream = ''.join(key[i % len(key)]  for i in range(len(msg)))
        print ('Your stream key is: ',key)

        plain_num = [ord(c) for c in msg]
        key_num = [ord(c) for c in keystream]
        
        added_num = list(map(add, plain_num, key_num))
        cipher_num = [i % 128 for i in added_num]

        # 加密结果转Base64编码(全可打印字符)
        encrypted_bytes = bytes(cipher_num)
        encrypted_b64 = base64.b64encode(encrypted_bytes).decode('utf-8')
        
        print ('Your encrypted text (Base64) is below:')
        print (encrypted_b64)
        
        
    elif select.lower() == 'd':
        cipher_b64 = input ('Enter cipher text (Base64) to decrypt: ')
        # 先解码Base64
        try:
            cipher_bytes = base64.b64decode(cipher_b64)
            cipher_txt_num = list(cipher_bytes)
        except:
            print('Invalid Base64 input!')
            continue

        cipher_key = input ('Enter key used to encrypt the text: ')
        keystream_txt = ''.join(cipher_key[i % len(cipher_key)]  for i in range(len(cipher_bytes)))
        cipher_key_num = [ord(c) for c in keystream_txt]

        # 简化解密逻辑:直接用模运算处理负数情况
        subtracted_ciphers = [(a - b) % 128 for a, b in zip(cipher_txt_num, cipher_key_num)]

        print ('Your decrypted text is below:')
        print (''.join(map(chr,subtracted_ciphers)))

额外优化说明

  1. 移除原解密逻辑中冗余的cipher_txt_num_added = ([i + 128 for i in cipher_txt_num]),直接使用(a - b) % 128即可正确处理a < b时的负数情况,模运算会自动转换为合法的ASCII正数值。
  2. Base64编码后,加密输出仅包含字母、数字和+/=符号,完全适配终端的输入规则,彻底解决跨环境的密文传递问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:57:09