首页 > 解决方案 > 创建加解密程序

问题描述

我需要有人编辑我的代码来调试它。它不会显示任何我认为是因为格式混乱但我不知道的加密或解密文本。如果您能提供帮助,将不胜感激。(我必须包括功能和用户输入)

result = ''
text = ''


text = input("Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
def toList(text):
  text.split()
  return text

decrypted = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
encrypted = b"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM "

encrypt_table = bytes.maketrans(decrypted, encrypted)
decrypt_table = bytes.maketrans(encrypted, decrypted)

text = input('Enter message for encryption: ')
def encrypt(text):
  result = ''
  text = ''
  result = text.translate(encrypt_table)
  print(result + '\n\n')


cipherText = input('Enter message to decrypt: ')
def decrypt(cipherText):
    result = ''
    message = ''
    result = message.translate(decrypt_table)
    print(result + '\n\n')


if text == '1':
  encrypt(text)
  print(result + '\n\n')
elif text == '2':
  decrypt(cipherText)

elif text != '0':
  print('You have entered an invalid input, please try again. \n\n')

标签: pythonencryption

解决方案


你有很多困惑。看encrypt,例如。您传入text,然后立即设置text='',从而破坏输入的消息。同样,在 中decrypt,您传入cipherText,但运行message.translate。并且您的函数需要返回它们的结果,而不是打印它们。让调用者决定如何处理返回的结果。

此外,在模块顶部收集函数是一种很好的做法,因此您不会自欺欺人地相信事情是以错误的顺序调用的。

这是您的代码,经过修改后可以正常工作:

def encrypt(text):
    result = text.translate(encrypt_table)
    return result

def decrypt(message):
    result = message.translate(decrypt_table)
    return result

decrypted = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
encrypted = b"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM "

encrypt_table = bytes.maketrans(decrypted, encrypted)
decrypt_table = bytes.maketrans(encrypted, decrypted)

while True:
    text = input("Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")

    if text == '1':
        text = input('Enter message for encryption: ')
        result =  encrypt(text)
        print(result)
    elif text == '2':
        cipherText = input('Enter message to decrypt: ')
        result = decrypt(cipherText)
        print(result)
    elif text == '0':
        break
    else:
        print('You have entered an invalid input, please try again. \n\n')

请注意,encrypt实际上decrypt并不需要存储在临时变量中。这样做的唯一原因是因为它更方便调试,print(result)return.


推荐阅读