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

如何用string库加密句子?加密解密程序解密异常排查求助

问题解答:字符串加密解密异常及string库加密方法

一、加密解密程序的bug修复

你的程序核心问题在于用random.choice生成映射表时会产生重复字符,导致加密字典dict1的键值对不是一一映射(重复的l2元素会覆盖之前的映射),解密时的反向字典dict2也会因为l2重复而丢失正确的映射关系,最终解密结果错误。

比如加密时,l1中的两个不同字符可能被映射到同一个l2字符,解密时这个字符只能对应回最后一个被映射的原字符,导致其他字符无法正确还原。

修复后的代码如下:

import random
import string

while True:
    print("What do you want to do? \n \t1) str to code \n \t2) code to str \n \t3) exit")
    answer = input("Tell me your answer:")
    
    if answer == "1":
        sentence = input("What sentence do you want to be coded?")
        list_sentence = list(sentence)
        # 定义完整字符集
        char_set = list(string.ascii_letters + string.digits + string.punctuation)
        # 复制字符集用于生成随机排列
        shuffled_chars = char_set.copy()
        
        random.seed(len(list_sentence))  # 用句子长度作为密钥种子
        random.shuffle(shuffled_chars)  # 洗牌生成唯一映射的字符列表
        
        # 生成加密字典:原字符→洗牌后的字符
        encrypt_dict = dict(zip(char_set, shuffled_chars))
        
        # 加密过程
        encrypted_chars = [encrypt_dict[c] if c in encrypt_dict else c for c in list_sentence]
        encrypted_message = ''.join(encrypted_chars)
        print("Encrypted message:", encrypted_message)
        print(f"Your key to unlock the code is {len(list_sentence)}") 
        break
    
    elif answer == "2":
        input_coded_sentence = input("What is your coded sentence?")
        key = int(input("What is your key to break the code?"))
        list_input = list(input_coded_sentence)
        
        char_set = list(string.ascii_letters + string.digits + string.punctuation)
        shuffled_chars = char_set.copy()
        
        random.seed(key)  # 使用相同密钥生成一致的映射表
        random.shuffle(shuffled_chars)
        
        # 生成解密字典:洗牌后的字符→原字符
        decrypt_dict = dict(zip(shuffled_chars, char_set))
        
        # 解密过程
        decrypted_chars = [decrypt_dict[c] if c in decrypt_dict else c for c in list_input]
        decrypted_message = ''.join(decrypted_chars)
        print("Decrypted message:", decrypted_message)
        break
    
    elif answer == "3":
        print("Goodbye!")
        break
    
    else:
        print("What are you doing?")

关键修复点:

  • 用random.shuffle()替代random.choice()生成映射表,确保每个字符唯一对应,避免重复覆盖
  • 修正了变量名拼写错误(sentense→sentence)
  • 用列表推导式简化加密解密循环,代码更简洁
  • 统一字符集定义,避免重复代码

二、如何使用string库对句子进行加密

基于string库,常用的加密方式有两种:

1. 单表替换加密(如上述修复后的方案)

利用string.ascii_letters、string.digits、string.punctuation获取完整字符集,通过随机洗牌生成唯一映射表,实现单表替换加密:

  • 步骤:
    • 组合string库提供的字符常量,定义需要加密的字符集合
    • 用固定种子生成一致的随机排列映射表(确保加密解密规则统一)
    • 生成原字符与加密字符的一一映射字典
    • 遍历句子,替换每个字符完成加密

2. 凯撒加密(移位加密)

针对字母进行固定移位,结合string库的字符序列实现:
示例代码:

import string

def caesar_encrypt(sentence, shift):
    # 生成字母表的移位映射
    lower = string.ascii_lowercase
    upper = string.ascii_uppercase
    shifted_lower = lower[shift:] + lower[:shift]
    shifted_upper = upper[shift:] + upper[:shift]
    # 合并映射字典
    encrypt_dict = dict(zip(lower + upper, shifted_lower + shifted_upper))
    # 加密
    return ''.join([encrypt_dict[c] if c in encrypt_dict else c for c in sentence])

def caesar_decrypt(ciphertext, shift):
    # 解密是移位的逆操作,用负移位实现
    return caesar_encrypt(ciphertext, -shift)

# 使用示例
plaintext = "I am amirreza"
shift = 13
cipher = caesar_encrypt(plaintext, shift)
print("加密后:", cipher)
print("解密后:", caesar_decrypt(cipher, shift))

这种方式仅针对字母移位,数字和符号可根据需求添加对应移位规则,实现更简单的加密逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 11:54:50