如何用Python Fernet库读取并解密记事本中的加密数据
使用Fernet解密文件内容失败的问题排查与修复
问题根源分析
你的代码存在4个核心问题,导致解密操作失败:
加密内容存储格式错误
写入文件时将Fernet加密后的bytes对象直接转成字符串(str(FileEncrypted)),导致存储内容包含Python字节串标识b'...'。比如原加密内容是b'gAAAAABk...',转成字符串后变成"b'gAAAAABk...'",解密时会把b'和'也当作密文的一部分,Fernet无法识别。解密方法调用错误
代码中使用Fernet.decrypt(f, num)是错误用法,应该用已初始化的Fernet实例f调用decrypt方法,即f.decrypt(...),而非通过类直接调用。文件读取逻辑混乱
解密分支中,for line in File已经在逐行迭代文件,后续又调用File.readline(),会直接跳过一行内容,导致描述和加密内容读取错位。同时读取到的加密字符串未处理掉多余的b标识和引号。文件写入未添加换行符
写入文件时,File.write(f"{EncryptionDescription}\n" + str(FileEncrypted))末尾未加换行,导致下一次写入的描述会和上一次的加密内容连在同一行,造成读取混乱。
修正后的代码
from cryptography.fernet import Fernet from inspect import currentframe key = "kdQGjocgILOLXj6k_mkkOJOxHxXJji7kdRUTtrGZBTo=" f = Fernet(key) def get_linenumber(): cf = currentframe() return cf.f_back.f_lineno def Main(): choice = input("1. Write Raw Data To File For Encryption\n2. Read Data From File For Decryption\n\nEnter Option Here: ") if choice == "1": print("Init Main Successfull On Line ", get_linenumber()) # 用with语句自动管理文件关闭,避免遗漏 with open(r"D:\Visual Studio Projects\Python Proj\Secure Note Storage Project\File.txt", mode="ab") as File: FileToEncrypt = bytes(input("Input data to encrypt, Note it will be stored as bytes, then encrypted with Fernet.\n"), 'utf-8') print("\nSuccesfully got File To Encrypt data on line ", get_linenumber(), "\nData From FileToEncrypt Var: ", FileToEncrypt) FileEncrypted = f.encrypt(FileToEncrypt) print("\n\nHere is the final product: ", FileEncrypted) EncryptionDescription = input("What Is The Data Entered. (Explain For Future Reference!!!)\n\nEnter Here: ") # 直接写入bytes格式的加密内容,每组数据添加换行分隔 File.write(f"{EncryptionDescription}\n".encode('utf-8')) File.write(FileEncrypted + b"\n") elif choice == "2": print("\n\nYou Have Chosen Decryption Method!\n") # 以rb模式读取文件(加密内容是bytes类型) with open(r"D:\Visual Studio Projects\Python Proj\Secure Note Storage Project\File.txt", mode="rb") as File: # 逐对读取描述行和加密行,避免迭代错位 while True: desc_line = File.readline() if not desc_line: break # 文件读取完毕 desc = desc_line.strip().decode('utf-8') encrypted_line = File.readline() if not encrypted_line: break encrypted_data = encrypted_line.strip() try: decrypted_data = f.decrypt(encrypted_data) print(f"描述: {desc}") print(f"解密后内容: {decrypted_data.decode('utf-8')}\n") except Exception as e: print(f"解密失败,原因: {str(e)}") print(f"问题行内容: {encrypted_data}\n") else: print("Sorry, We Do Not Recognise What You Have Entered. Please look at the options and think...") exit(0) if __name__ == "__main__": Main()
关键修改说明
- 存储优化:不再将加密
bytes转成字符串,直接以ab模式写入文件,避免引入多余字符;每组数据末尾添加换行,确保格式清晰。 - 读取逻辑修正:用
rb模式读取文件,通过while True循环逐对读取描述和加密内容,避免迭代与readline()混用导致的错位。 - 解密调用修正:使用实例方法
f.decrypt(encrypted_data),传入正确的bytes类型密文。 - 异常处理:添加
try-except捕获解密异常,方便快速定位问题。 - 文件管理:用
with语句自动关闭文件,避免资源泄漏。
内容的提问来源于stack exchange,提问作者user17096148
相关产品推荐
相关产品推荐

