0

I wrote a simple python script to encrypt (and then decrypt) a configuration file, using cryptography.fernet library. They work as expected on Linux systems, otherwise on Windows systems every time I decrypt the file it adds a newline in between every line. For example, if this is my config file:

[config]
user = test
psw = testtest

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

after encryption and then decryption, on Windows systems it becomes like this:

[config]

user = test

psw = testtest


[utils]

ip = xx.xx.xx.xx

Sometimes after this behavior the script doesn't work, for it everything is on the same line.

Is it an encoding issue?

This is the encryption script:

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

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

try:
    # generate key
    key = Fernet.generate_key()

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

    # encrypt data
    fernet = Fernet(key)
    encrypted = fernet.encrypt(data)

    # write encrypted file
    with open(encrypted_file, "wb") as f :
        f.write(encrypted)

    # write file with key
    with open(key_file, "wb") as f :
        f.write(key)

except Exception as error :
   print(f"Error: {error}")

And this is the decryption script:

#!/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()

    # write file unencrypted
    with open(decrypted_file, "w") as f :
        f.write(decrypted)
    
except Exception as error :
    print(f"Error: {error}")

Thanks in advance for any help.

  • 1
    Did you try writing with "wb" instead of "w"? Binary mode is writing the plaintext byte-by-byte, while "w" will write things as text, and end-of-line conversion routines are exactly what you should expect. Best to treat all the files as binary if you want to have a 1:1 plaintext. – Maarten Bodewes Apr 14 '23 at 15:50
  • In text mode, the conversion of newlines can be controlled with the [`newline`](https://docs.python.org/3/library/functions.html#open) parameter. By default, when writing newline related characters are replaced by [`os.linesep`](https://docs.python.org/3/library/os.html#os.linesep), which contains `\r\n` for Windows. With `open(..., newline='')` this should be avoided. However, binary mode seems to be the simpler (and more consistent) solution here (for this, the decrypted data must not be decoded). – Topaco Apr 14 '23 at 18:55

0 Answers0