How to implement Python file encryption and decryption.
Encrypting and decrypting Python files can be achieved by using encryption algorithms and the corresponding keys. Here is a simple example:
Encrypting files:
from cryptography.fernet import Fernet
def encrypt_file(file_path, key):
with open(file_path, 'rb') as file:
data = file.read()
fernet = Fernet(key)
encrypted_data = fernet.encrypt(data)
with open(file_path, 'wb') as file:
file.write(encrypted_data)
# 使用一个随机生成的密钥
key = Fernet.generate_key()
# 加密文件
encrypt_file('plain.txt', key)
Decrypt document:
from cryptography.fernet import Fernet
def decrypt_file(file_path, key):
with open(file_path, 'rb') as file:
encrypted_data = file.read()
fernet = Fernet(key)
decrypted_data = fernet.decrypt(encrypted_data)
with open(file_path, 'wb') as file:
file.write(decrypted_data)
# 使用之前生成的密钥
key = b'your_generated_key'
# 解密文件
decrypt_file('encrypted.txt', key)
上述示例使用了cryptography库中的Fernet算法来进行文件加密和解密。在加密时,读取文件内容并使用密钥对其进行加密,然后将加密后的数据写回到文件中。在解密时,读取加密后的文件内容并使用密钥对其进行解密,然后将解密后的数据写回到文件中。请注意,密钥需要在加密和解密时保持一致。
It is important to note that file encryption and decryption is a basic method of protecting file content, but it does not prevent other types of attacks or ensure the integrity of files. It is crucial to ensure the security of the key when using file encryption and decryption.