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

Windows系统下Fernet加解密文件出现多余空行问题求助

Windows下Fernet解密配置文件后每行出现空行问题

问题描述

使用cryptography.fernet编写的加密/解密脚本在Linux上运行正常,但在Windows系统中,解密后的配置文件每行之间会新增空行,导致脚本有时无法正常识别内容。

原配置文件内容:

[config]
user = test
psw = testtest

[utils]
ip = xx.xx.xx.xx

Windows解密后内容:

[config]

user = test

psw = testtest


[utils]

ip = xx.xx.xx.xx

问题原因

这不是编码问题,而是Windows与Linux的换行符格式差异导致的:

  • Linux系统使用\n作为换行符,Windows系统使用\r\n作为换行符。
  • 加密脚本以二进制模式(rb)读取文件,完整保留了原文件的换行符格式(比如原Linux格式文件的\n)。
  • 解密脚本中,先将解密后的二进制数据解码为字符串,再以文本模式(w)写入文件:Windows下的文本模式会自动将字符串中的\n转换为\r\n。如果原文件是Windows格式(\r\n),解码后字符串包含\r\n,写入时文本模式又把\n转成\r\n,最终变成\r\r\n,显示为每行之间的空行。

解决方案

方案1:统一使用二进制模式处理解密后写入

修改解密脚本,直接写入二进制数据,避免系统自动转换换行符:

#!/usr/bin/env python
from cryptography.fernet import Fernet

# variables
key_file = r"key_file.txt"
encrypted_file = r"configFile.txt"
decrypted_file = r"configFile.txt"

try:
    # read key file
    with open(key_file, "rb") as k :
        key = k.read()

    # read encrypted file
    with open(encrypted_file, "rb") as f :
        data = f.read()

    # decrypt file - 保留二进制,不提前解码
    fernet = Fernet(key)
    decrypted = fernet.decrypt(data)

    # 以二进制模式写入文件
    with open(decrypted_file, "wb") as f :
        f.write(decrypted)
    
except Exception as error :
    print(f"Error: {error}")

方案2:文本模式写入时禁用换行符自动转换

如果需要用文本模式写入,指定newline=''参数,让Python保留原始换行符:

#!/usr/bin/env python
from cryptography.fernet import Fernet

# variables
key_file = r"key_file.txt"
encrypted_file = r"configFile.txt"
decrypted_file = r"configFile.txt"

try:
    # read key file
    with open(key_file, "rb") as k :
        key = k.read()

    # read encrypted file
    with open(encrypted_file, "rb") as f :
        data = f.read()

    # decrypt file
    fernet = Fernet(key)
    decrypted = fernet.decrypt(data).decode('utf-8')  # 指定明确编码

    # 写入文件时禁用自动换行转换
    with open(decrypted_file, "w", newline='', encoding='utf-8') as f :
        f.write(decrypted)
    
except Exception as error :
    print(f"Error: {error}")

额外建议

  • 加密和解密全程使用二进制模式处理,能彻底避免换行符和编码的潜在问题。
  • 解码时指定明确的编码(如utf-8),不要依赖系统默认编码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 19:27:07