python - 创建加解密程序
问题描述
我需要有人编辑我的代码来调试它。它不会显示任何我认为是因为格式混乱但我不知道的加密或解密文本。如果您能提供帮助,将不胜感激。(我必须包括功能和用户输入)
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')
解决方案
你有很多困惑。看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
.
推荐阅读
- yaml - 如何在heat模板中使用horizon中存在的安全组
- opencv - 从非固定摄像机镜头中减去背景
- python - Python 使用枢轴重塑数据框。索引不出现
- elasticsearch - 在对象列表中检索受字段值限制的项目
- html-framework-7 - 如何在 html 文件中迭代数组并在 Framework7 V1 中查看其元素?
- amazon-web-services - 如何引导我的 EC2 网络服务器连接到 Chef GUI 页面?它说节点的地方
- javascript - Webpack / ES6 动态导入
- java - Spring Boot:找不到处理程序方法
- encryption - 可以在 ConnectyCube 中对视频通话和聊天进行端到端加密吗?
- html - 图像在宽度缩小时不会调整高度