【发布时间】:2021-02-16 03:30:12
【问题描述】:
我想在 python3 程序中创建一个文件,我想在其中存储一些我不希望用户看到或操作的信息。但是,在执行时我需要读取和修改它的内容,确保用户不能修改文件的内容。我怎样才能做到这一点?
【问题讨论】:
标签: python encryption cryptography pycrypto
我想在 python3 程序中创建一个文件,我想在其中存储一些我不希望用户看到或操作的信息。但是,在执行时我需要读取和修改它的内容,确保用户不能修改文件的内容。我怎样才能做到这一点?
【问题讨论】:
标签: python encryption cryptography pycrypto
您可以将私有信息存储在 python 对象中,例如字典等然后编译(.py-->.pyc),加密源文件(.py-->.py.cpt)最后发布仅编译后的文件,可选择使用其加密对(同时将加密密钥安全地保存给自己)。
您可以找到更多详细信息here。
【讨论】:
在此示例中,我使用了 Fernet 和使用密码“硬编码”创建的密钥。 您可以加密文件并仅在必要时解密其中的信息。 如果你必须修改信息,你可以再次调用加密函数。
from cryptography.fernet import Fernet
import base64, hashlib
def encrypt(filename, key):
f = Fernet(key)
with open(filename, "rb") as file:
# read the encrypted data
file_data = file.read()
# encrypt data
encrypted_data = f.encrypt(file_data)
# write the encrypted file
with open(filename, "wb") as file:
file.write(encrypted_data)
def decrypt(filename, key):
f = Fernet(key)
with open(filename, "rb") as file:
# read the encrypted data
encrypted_data = file.read()
# decrypt data
decrypted_data = f.decrypt(encrypted_data)
print(decrypted_data)
my_password = 'mypassword'.encode()
key = hashlib.md5(my_password).hexdigest()
key_64 = base64.urlsafe_b64encode(key.encode("utf-8"))
# file name
file = "test.txt"
# encrypt it
encrypt(file, key_64)
with open("test.txt", "rb") as f:
print(f.read())
decrypt(file, key_64)
【讨论】: