cryptography库中的Fernet模块提供了一种简单的方法来加密和解密数据。它使用对称加密算法,其中相同的密钥用于加密和解密数据。以下是用Fernet模块对文件进行的加密和解密。
加密:
import hashlib
import base64
from cryptography.fernet import Fernet
import os
def string_to_fernet_key(input_string):
# 使用SHA-256哈希函数生成一个固定长度的字节串
hash_object = hashlib.sha256(input_string.encode())
hash_digest = hash_object.digest()
# 截取前32字节
key_bytes = hash_digest[:32]
# 将字节转换为URL-safe base64编码
base64_key = base64.urlsafe_b64encode(key_bytes)
return base64_key.decode('utf-8')
def encrypt_file(file_path, key):
f = Fernet(key)
base_name = os.path.splitext(os.path.basename(file_path))[0]
new_file_path = os.path.join(os.path.dirname(file_path), base_name)
with open(file_path, 'rb') as file:
original_data = file.read()
encrypted_data = f.encrypt(original_data)
with open(new_file_path + '.byte', 'wb') as encrypted_file:
encrypted_file.write(encrypted_data)
os.remove(file_path)
def encrypt_directory(directory_path, key):
for root, dirs, files in os.walk(directory_path):
for file in files:
file_path = os.path.join(root, file)
encrypt_file(file_path, key)
# 使用
key = string_to_fernet_key("密钥")
print(key)
directory_to_encrypt = '文件夹路径'
encrypt_directory(directory_to_encrypt, key)
解密:
import hashlib
import base64
from cryptography.fernet import Fernet
import os
def string_to_fernet_key(input_string):
# 使用SHA-256哈希函数生成一个固定长度的字节串
hash_object = hashlib.sha256(input_string.encode())
hash_digest = hash_object.digest()
# 截取前32字节
key_bytes = hash_digest[:32]
# 将字节转换为URL-safe base64编码
base64_key = base64.urlsafe_b64encode(key_bytes)
return base64_key.decode('utf-8')
def decrypt_file(file_path, key):
"""
解密指定路径的文件,假设原始文件为 Python 文件,解密后添加 .py 后缀。
"""
f = Fernet(key)
print(f)
# 构建新文件的完整路径,假设原始文件是 Python 文件
base_name = os.path.splitext(os.path.basename(file_path))[0]
new_file_path = os.path.join(os.path.dirname(file_path), base_name + ".py")
with open(file_path, 'rb') as file:
encrypted_data = file.read()
decrypted_data = f.decrypt(encrypted_data)
with open(new_file_path, 'wb') as decrypted_file:
decrypted_file.write(decrypted_data)
os.remove(file_path)
def decrypt_directory(directory_path, key):
"""
递归解密指定目录下的所有文件。
"""
for root, dirs, files in os.walk(directory_path):
for file in files:
if file.endswith('.byte'): # 只解密以 .byte 结尾的文件
file_path = os.path.join(root, file)
decrypt_file(file_path, key)
# 使用
key = string_to_fernet_key("密钥")
directory_to_decrypt = '文件夹路径'
decrypt_directory(directory_to_decrypt, key)