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

Python简易密码加解密代码问题:解密后仅部分字符正确

密码加密解密程序问题排查与修复建议

问题描述

我是一名Python新手,编写了两个版本的程序,用于生成密码、“加密”密码和解密密码(我知道这并非真正的加密,只是想实现基础逻辑并学习新内容)。但目前遇到问题:加密后再解密,仅半数字符正确。我已尝试多种方法仍未解决,附上两个版本的代码,恳请帮助排查问题并提供建议。

版本1代码

import random as rd
def psw_encryption():
  str_list = str.maketrans({"a": "b","6": "b","m": "c","g": "d","n": "e","l": "f","y": "g","e": "h","i": "k","h": "j","o": "k","v": "l","z": "m","t": "n","0": "o","d": "p","r": "q","q": "r","f": "s","u": "t","j": "u","c": "f","k": "w","i": "x","a": "z","5": "z","4": "9","s": "5","x": "3","8": "5","9":"6","3": "2","7": "9","p": "0", "8": "x"})
  print("What is your password?")
  psw = str(input())
  psw_new = psw.translate(str_list)
  print("Your encrypted password is: ",psw_new + "di29ens92ned")
  print("If you want to decrypt it then just use the decrypter.")
def psw_decrypt():
  str_list = str.maketrans({"b": "a","b": "6","c": "m","d": "g","e": "n","f": "l","g": "y","h": "e","k": "i","j": "h","k": "o","l": "v","m": "z","n": "t","o": "0","p": "d","q": "r","r": "q","s": "f","t": "u","u": "j","f": "c","w": "k","x": "i","z": "a","z": "5","9": "4","5": "s","3": "x","5": "8","6":"9","2": "3","9": "7","0": "p", "x": "8"})
  print("what is your encrypted password?")
  psw = str(input())
  psw = psw.replace("di29ens92ned", "")
  psw_old = psw.translate(str_list)
  print("Your decrypted password is:", psw_old)
def psw_gen():
  abc123_list = ["1","2","3","4","5","6","7","8","9","0","q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"]
  print("Your Super Secret password is:",''.join([rd.choice(abc123_list) for _ in range(13)]))

print("What do you want to do?")
print("1/ Generate a Super Secret password.")
print("2/ Encrypt your password.")
print("3/ Decrypt your password")
choice_ = int(input("Put your choice here: "))

if choice_ == 1:
  psw_gen()
elif choice_ == 2:
  psw_encryption()
elif choice_ == 3:
  psw_decrypt()
else:
  print("Invalid input!")

list2 = ["b 6 m g n l y e h o 1 v z t 2 0 d q r f u j c k i a 5 4 s x 8 9 3 7 p"]
#1234567890qwertyuiopasdfghjklzxcvbnm

版本2代码

import random as rd #7bqia

def psw_encryption():
    str_list = str.maketrans("ba6mglnyehovzt20dqrfuicka549sx8973p", "bzcdjklmnot0rqfujhievx58936psawygzd")
    print("What is your password?")
    psw = input()
    psw_new = psw.translate(str_list)
    print("Your encrypted password is:", psw_new)
    print("If you want to decrypt it then just use the decrypter.")

def psw_decrypt():
    str_list = str.maketrans("bzcdjklmnot0rqfujhievx58936psawygzd", "ba6mglnyehovzt20dqrfuicka549sx8973p")
    print("what is your encrypted password?")
    psw = input()
    psw_old = psw.replace("di29ens92ned", "")
    psw_old = psw_old.translate(str_list)
    print("Your decrypted password is:", psw_old)

def psw_gen():
    abc123_list = ["1","2","3","4","5","6","7","8","9","0","q","w","e","r","t","y","u","i","o","p",
                   "a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"]
    print("Your Super Secret password is:", ''.join([rd.choice(abc123_list) for _ in range(13)]))

print("What do you want to do?")
print("1/ Generate a Super Secret password.")
print("2/ Encrypt your password.")
print("3/ Decrypt your password")

choice_ = int(input("Put your choice here: "))
if choice_ == 1:
    psw_gen()
elif choice_ == 2:
    psw_encryption()
elif choice_ == 3:
    psw_decrypt()
else:
    print("Invalid input!")

问题排查

版本1核心问题

  • 字典键重复覆盖:str.maketrans的字典参数中,同一个键被多次定义(比如加密字典里"a": "b"和"a": "z",后者会直接覆盖前者),导致部分字符的加密映射完全错误;解密字典同理,比如"b": "a"和"b": "6",最终只有后者生效,解密时无法还原原字符。
  • 映射逻辑不互逆:多个原字符映射到同一个加密字符(比如"a"和"5"都映射到"z"),解密时无法区分原字符,必然导致还原错误。

版本2核心问题

  • 映射字符串长度不匹配:str.maketrans的双字符串参数必须长度完全一致,版本2中加密的源字符串和目标字符串长度不同,会导致部分映射规则被忽略,加密解密逻辑直接错乱。
  • 后缀处理逻辑矛盾:版本2加密时没加di29ens92ned后缀,但解密函数依然执行移除操作,若密码本身包含该字符串片段,会被错误删除。

修复方案与优化代码

修复原则

  1. 确保加密解密映射一一对应,每个原字符对应唯一加密字符,且加密字符能反向还原原字符。
  2. 统一后缀处理逻辑,要么加密时统一添加,解密时统一移除,要么都不添加。
  3. 增加输入合法性校验,避免非数字输入导致程序崩溃。

修复后的代码

import random as rd

# 定义一一对应的加密解密映射,确保长度一致
ORIGIN_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789"
ENCRYPT_CHARS = "zyxwvutsrqponmlkjihgfedcba9876543210"

def psw_encryption():
    str_trans = str.maketrans(ORIGIN_CHARS, ENCRYPT_CHARS)
    print("请输入你的密码:")
    psw = input().strip()
    encrypted_psw = psw.translate(str_trans) + "di29ens92ned"  # 统一添加后缀
    print(f"加密后的密码:{encrypted_psw}")
    print("如需解密请使用解密功能。")

def psw_decrypt():
    str_trans = str.maketrans(ENCRYPT_CHARS, ORIGIN_CHARS)
    print("请输入加密后的密码:")
    encrypted_psw = input().strip()
    # 先移除后缀,再解密
    raw_psw = encrypted_psw.replace("di29ens92ned", "")
    decrypted_psw = raw_psw.translate(str_trans)
    print(f"解密后的密码:{decrypted_psw}")

def psw_gen():
    abc123_list = list("abcdefghijklmnopqrstuvwxyz0123456789")
    print("生成的随机密码:", ''.join([rd.choice(abc123_list) for _ in range(13)]))

print("请选择操作:")
print("1/ 生成随机密码")
print("2/ 加密密码")
print("3/ 解密密码")
try:
    choice_ = int(input("输入你的选择:"))
    if choice_ == 1:
        psw_gen()
    elif choice_ == 2:
        psw_encryption()
    elif choice_ == 3:
        psw_decrypt()
    else:
        print("无效输入!")
except ValueError:
    print("请输入有效数字!")

额外学习建议

  • 仔细阅读str.maketrans的官方说明,明确字典方式和双字符串方式的使用规则:双字符串必须长度相同,字典方式不能有重复键。
  • 先从简单的凯撒密码入手,理解加密解密的互逆性核心逻辑,再逐步扩展复杂映射。
  • 调试时可以打印生成的映射表,检查每个字符的对应关系是否符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 06:34:55