You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的密码管理器程序无法创建存储加密主密码的文件?

问题分析与修复

你的代码存在几个关键问题导致文件无法生成,同时Fernet加密逻辑完全错误,以下是具体问题和修复方案:

1. Fernet库使用错误

你导入的fernet不是正确的库,正确的是cryptography库中的Fernet模块,且其API用法完全不是你代码中的Encrypter/Decrypter:

  • 首先需要安装依赖:pip install cryptography
  • 正确用法是先生成Fernet密钥,用密钥创建加密实例;加密/解密的内容必须是字节串,解密后需要转回字符串。
  • 注意:Fernet加密依赖密钥,你需要妥善存储这个密钥(比如单独存文件),否则无法解密主密码。

2. 文件存在性判断未实时更新

doesMasterPasswordExist只在程序启动时判断一次,即使创建了文件,循环内依然会走首次启动分支,必须把判断放到循环内部,每次循环都检查文件是否存在。

3. 文件操作不规范

直接用open()后手动关闭容易出现资源泄漏,建议使用with语句自动管理文件上下文。

修复后的代码

import os
from cryptography.fernet import Fernet

masterPasswordFile = 'mstrpswd.faiK'
keyFile = 'fernet_key.key'

# 生成并保存Fernet密钥(首次运行时生成)
def generate_key():
    if not os.path.exists(keyFile):
        key = Fernet.generate_key()
        with open(keyFile, 'wb') as f:
            f.write(key)

# 加载Fernet密钥
def load_key():
    return open(keyFile, 'rb').read()

generate_key()
fernet = Fernet(load_key())

while True:
    # 每次循环都检查文件是否存在
    doesMasterPasswordExist = os.path.exists(masterPasswordFile)
    
    if not doesMasterPasswordExist:
        print('Looks like it`s your first time, please set up a master password before we get started.')
        masterPassword = input('--> ')
        
        # 加密主密码(转成字节串)
        masterPassword_encrypted = fernet.encrypt(masterPassword.encode())
        # 用with语句写入文件
        with open(masterPasswordFile, 'wb') as newFile:
            newFile.write(masterPassword_encrypted)
        print("Master password set successfully!")
        continue
    else:
        print('What is your master password?')
        user_mstrpswd = input('--> ')
        with open(masterPasswordFile, 'rb') as mstrpswdFile:
            masterPassword_encrypted_readFromFile = mstrpswdFile.read()
        
        try:
            # 解密并转回字符串
            mstrpswd_decrypted = fernet.decrypt(masterPassword_encrypted_readFromFile).decode()
        except:
            print('Invalid password or corrupted file!')
            continue
        
        if mstrpswd_decrypted != user_mstrpswd:
            print('That`s not right, try again.')
            continue
        else:
            print('You`re in!')
            break  # 验证通过后退出循环,进入后续逻辑

关键修复说明

  • 新增Fernet密钥的生成和存储逻辑,这是Fernet加密的核心,没有密钥无法解密。
  • 将文件存在性判断移到循环内部,确保创建文件后下一次循环会切换到登录分支。
  • 使用with语句处理文件IO,避免资源泄漏。
  • 修正加密/解密的字节串转换逻辑,符合Fernet的API要求。
  • 添加异常捕获,处理解密失败的情况(比如密码错误或文件损坏)。

内容的提问来源于stack exchange,提问作者dll

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 10:12:57