一、环境准备
1.1 安装Python
确保安装Python3.8+环境,官方下载地址:https://www.python.org/downloads/,安装时务必勾选「Add Python to PATH」选项。
1.2 安装依赖库
打开终端执行以下命令,安装加密所需的成熟工具包:
```
pip install cryptography python-dotenv
```
cryptography提供工业级加密算法,python-dotenv用于安全存储密钥,避免硬编码泄露。
二、编写核心管理脚本
新建文件命名为archive_manager.py,复制以下完整代码(直接运行即可,无需修改):
```python
import os
from dotenv import load_dotenv
from cryptography.fernet import Fernet
加载加密密钥,首次运行自动生成
load_dotenv()
ENCRYPT_KEY = os.getenv("ENCRYPT_KEY")
if not ENCRYPT_KEY:
key = Fernet.generate_key()
with open(".env", "wb") as f:
f.write(b"ENCRYPT_KEY=" + key + b"\n")
ENCRYPT_KEY = key
print("首次运行已生成密钥,密钥存储于.env文件,请备份!")
fernet = Fernet(ENCRYPT_KEY)
def encrypt_single(file_path):
"""加密单个档案文件"""
if not os.path.exists(file_path):
print(f"错误:文件{file_path}不存在")
return
try:
with open(file_path, "rb") as f:
data = f.read()
encrypted = fernet.encrypt(data)
enc_path = f"{file_path}.enc"
with open(enc_path, "wb") as f:
f.write(encrypted)
取消下一行注释可删除原始文件
os.remove(file_path)
print(f"加密完成:{enc_path}")
except Exception as e:
print(f"加密失败:{str(e)}")
def decrypt_single(enc_path):
"""解密单个加密文件"""
if not enc_path.endswith(".enc"):
print("错误:仅支持.enc格式加密文件")
return
if not os.path.exists(enc_path):
print(f"错误:加密文件{enc_path}不存在")
return
try:
with open(enc_path, "rb") as f:
enc_data = f.read()
decrypted = fernet.decrypt(enc_data)
orig_path = enc_path[:-4]
with open(orig_path, "wb") as f:
f.write(decrypted)
print(f"解密完成:{orig_path}")
except Exception as e:
print(f"解密失败:密钥错误或文件损坏,错误:{str(e)}")
def list_archives(folder="."):
"""列出当前目录所有档案文件"""
print("=== 当前档案列表 ===")
for f in os.listdir(folder):
if os.path.isfile(os.path.join(folder, f)):
print(f"- {f}")
if __name__ == "__main__":
print("=== 档案加密管理系统 ===")
print("操作选项:1.加密文件 2.解密文件 3.列出档案")
choice = input("输入选项编号:").strip()
if choice == "1":
path = input("输入要加密的文件路径:").strip()
encrypt_single(path)
elif choice == "2":
path = input("输入要解密的.enc文件路径:").strip()
decrypt_single(path)
elif choice == "3":
list_archives()
else:
print("无效选项,请输入1/2/3")
```
三、系统运行与操作
打开终端,进入脚本所在目录,执行启动命令:
```
python archive_manager.py
```
首次运行会自动生成.env密钥文件,务必备份该文件,丢失则无法解密所有加密文件!

按提示选择核心操作:
- 1.加密文件:输入要加密的文件路径(如
./公司档案.docx),生成带.enc后缀的加密文件
- 2.解密文件:输入带.enc的加密文件路径,自动解密为原格式文件
- 3.列出档案:显示当前目录所有文件,快速定位需操作的档案
四、进阶扩展(可选)
批量加密/解密
修改主程序(代码最后部分),添加批量逻辑,示例:批量加密当前目录所有PDF文件
```python
if choice == "1":
新增批量加密逻辑
for file in os.listdir("."):
if file.endswith(".pdf"):
encrypt_single(file)
```
修改后重新运行,自动批量处理对应格式的档案。
密钥备份
将.env文件复制到外接硬盘等安全位置,更换设备或重装系统时,替换新环境下的.env文件即可恢复解密权限。
五、核心注意事项
1. 密钥是唯一解密凭证,切勿与加密文件存放在同一目录,也不要泄露;
2. 加密文件仅支持本系统解密,不兼容其他加密工具;
3. 测试时务必复制原始文件,避免误操作丢失数据。