如何用Python的Fernet加密目录下指定文件(支持for循环实现)
用Fernet实现目录文件加密(替代BitLocker的Python脚本)
当然可以用for循环实现目录内目标文件的加密,先修正你原代码里的错误,再给出完整的加密实现:
原代码存在的问题
- 多密钥输入循环中,错误添加初始
passkey而非用户新输入的密钥 - 写入
passwords.txt时,二进制模式无法直接写入字符串列表 - 未保存生成的Fernet加密密钥,导致加密后无法解密
- 未排除密钥存储文件(如
encryption.key)
修正后的完整代码
# Script is named match_key.py from cryptography.fernet import Fernet import os # 初始化密钥列表 key_list = [] passkey = input("Enter your key: ") key_list.append(passkey) add_key = input("Do you want to enter another key? (y/N) ") # 处理多密钥输入 while add_key.lower() == "y": key = input("Enter your key: ") key_list.append(key) # 修正:添加新输入的密钥而非初始值 add_key = input("Do you want to enter another key? (y/N) ") # 保存密钥列表到文件(文本模式存储) with open("passwords.txt", "w") as passwords: passwords.write("\n".join(key_list)) print("已保存的密钥列表:", key_list) # 生成并保存Fernet加密密钥 fernet_key = Fernet.generate_key() with open("encryption.key", "wb") as key_file: key_file.write(fernet_key) cipher = Fernet(fernet_key) # 生成待加密文件列表(排除脚本本身和密钥文件) encr_file_list = [] for file in os.listdir(): if file in ["match_key.py", "passwords.txt", "encryption.key"]: continue if os.path.isfile(file): encr_file_list.append(file) print("待加密文件列表:", encr_file_list) # 用for循环加密每个目标文件 for file_path in encr_file_list: # 读取文件二进制内容 with open(file_path, "rb") as f: file_data = f.read() # 加密内容 encrypted_data = cipher.encrypt(file_data) # 将加密内容写回原文件(若需保留原文件,可改为写入带后缀的新文件,如file_path + ".enc") with open(file_path, "wb") as f: f.write(encrypted_data) print(f"已加密文件: {file_path}")
加密核心逻辑说明
- 遍历
encr_file_list中的每个文件路径,逐个处理 - 以二进制模式读取文件内容(Fernet仅支持字节数据加密)
- 调用
cipher.encrypt()完成加密 - 将加密后的字节数据覆盖原文件(或写入新文件)
注意事项
- 务必妥善保存
encryption.key:没有该密钥无法解密加密后的文件 - 当前代码中收集的
key_list仅做存储,若要实现类似BitLocker的多密钥解锁,还需额外逻辑将用户密钥与Fernet密钥关联(比如用用户密钥加密Fernet密钥)
内容的提问来源于stack exchange,提问作者Pork Lord
相关产品推荐
相关产品推荐

