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

writing a variable to a text file and encrypting it?

我知道如何将用户输入保存到文本文件,但我该如何加密呢?这是我将用户输入保存到文本文件的方法。我尝试了 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!")

我猜您想获得某种密码哈希值,但文件对象与此无关。您可以尝试使用 base64 编码(如 here),或任何其他同类算法。

您的代码:

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!")

查看 password hashing

那么我建议你使用 https://pythonhosted.org/passlib/ 或 pycrypto;取决于你选择的算法。

这只是为了存储加密后的密码。然后加密数据看看 https://pypi.python.org/pypi/pycrypto/2.6.1.

有一些 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)

你说过,你试过 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