随着信息技术的飞速发展,数据安全和个人隐私保护变得尤为重要。Python作为一种功能强大的编程语言,在数据加密方面也有着广泛的应用。本文将为您揭秘如何使用Python加密文件夹,实现一键安全存储,轻松...
随着信息技术的飞速发展,数据安全和个人隐私保护变得尤为重要。Python作为一种功能强大的编程语言,在数据加密方面也有着广泛的应用。本文将为您揭秘如何使用Python加密文件夹,实现一键安全存储,轻松守护隐私。
首先,您需要安装Python的加密库。以下是一个常用的加密库——cryptography。
pip install cryptography使用cryptography库生成一个密钥,用于加密和解密文件夹。
from cryptography.fernet import Fernet
# 生成密钥
key = Fernet.generate_key()
print("密钥:", key.decode())
# 将密钥保存到文件中
with open('secret.key', 'wb') as key_file: key_file.write(key)将文件夹中的所有文件加密。以下代码示例展示了如何加密指定文件夹中的所有文件。
import os
from cryptography.fernet import Fernet
# 加载密钥
with open('secret.key', 'rb') as key_file: key = key_file.read()
cipher_suite = Fernet(key)
# 加密文件夹
def encrypt_folder(folder_path, cipher_suite): for file in os.listdir(folder_path): file_path = os.path.join(folder_path, file) if os.path.isfile(file_path): with open(file_path, 'rb') as file: original_data = file.read() encrypted_data = cipher_suite.encrypt(original_data) with open(file_path, 'wb') as file: file.write(encrypted_data)
folder_path = 'path_to_your_folder'
encrypt_folder(folder_path, cipher_suite)当需要访问加密文件夹中的文件时,可以使用以下代码进行解密。
# 解密文件夹
def decrypt_folder(folder_path, cipher_suite): for file in os.listdir(folder_path): file_path = os.path.join(folder_path, file) if os.path.isfile(file_path): with open(file_path, 'rb') as file: encrypted_data = file.read() original_data = cipher_suite.decrypt(encrypted_data) with open(file_path, 'wb') as file: file.write(original_data)
decrypt_folder(folder_path, cipher_suite)通过以上步骤,您可以使用Python轻松加密和解密文件夹,实现数据的安全存储和隐私保护。