将变量写入文本文件并加密?

3

我知道如何将用户的输入保存到文本文件中,但如何加密它呢?以下是我用于将用户输入保存到文本文件中的代码。我尝试过f.encrypt("Passwords_log.txt",但没有结果。

import time
password1 = input("Please type a password: ")
print("Your password has passed the verification!")
time.sleep(1)
print("Saving and encrypting password...")
time.sleep(2)
f=open("Passwords_log.txt",'a')
f.write(password)
f.write('\n')
f.close()
print("Done!")

你在哪里看到 file.encrypt 的? :) 你可以在 Python 文档中阅读有关 文件对象 的更多信息。 - André Laszlo
你想要加密密码并保存到文件中,还是先将密码保存到文件中,再加密文件? - Avión
4个回答

4

有一些与加密相关的 Python 包值得关注。

Cryptography

PyCrypto

来自 cryptography 的一个简单示例如下:

from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt(b"A really secret message. Not for prying eyes.")
plain_text = cipher_suite.decrypt(cipher_text)

0

我猜你想为密码获取某种哈希值,但文件对象与此无关。你可以尝试使用base64编码(例如这里),或任何其他类似的算法。

你的代码:

import time
import base64
password1 = raw_input("Please type a password: ")
print("Your password has passed the verification!")
time.sleep(1)
print("Saving and encrypting password...")
time.sleep(2)
f=open("Passwords_log.txt",'a')
password = base64.b64encode(password)
f.write(password)
f.write('\n')
f.close()
print("Done!")

0

你说过,你尝试了base64但是没有成功。这里是让它工作的方法:

import base64
import time
password1 = input("Please type a password: ")
print("Your password has passed the verification!")
time.sleep(1)
print("Saving and encrypting password...")
time.sleep(2)
f=open("Passwords_log.txt",'a')
cr = base64.encodestring(password1)
f.write(cr)
f.write('\n')
f.close()
print("Done!")

这不是真正的加密,我不建议用于密码,但由于您在评论中说尝试使用base64并且它没有起作用,所以我想向您展示如何在代码中使用base64


就像@Joe R所说,Python可能不是加密的最佳选择。有关更多详细信息,请参阅crypto.stackexchange上的此答案。 http://crypto.stackexchange.com/a/19969 - Steven Correia

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接