0

Here is my code to encrypt the config.ini file which has sql connection details (username and pw) and some file paths.

from cryptography.fernet import Fernet
key = Fernet.generate_key()
i_file = 'conf.ini'
o_file = 'Conf_encry.ini'
with open(i_file,'rb') as f:
    data = f.read()
fernet = Fernet(key)
encrypt = fernet.encrypt(data)
with open(o_file,'wb') as f:
    f.write(encrypt)
print(key)

This will encrypt my file to Conf_encry.ini And this is my code to decrypt the Conf_encry.ini file

from cryptography.fernet import Fernet
k_file = 'key.txt'
i_file = 'Conf_encry.ini'
with open(k_file, 'rb') as k:
    key = k.read()
with open(i_file, 'rb') as f:
    data = f.read()
fernet = Fernet(key)
decry = fernet.decrypt(data)
print(decry)

But problem is after decrypting the i_file its getting converted into usual txt file with lots of \r , \n and spaces. And that's why code (configparser) which reads this conf file as dict gives an error

# Original Configuration file before encrypt
[ABC]
host=   a01        
port = 1234
database = DB_1
user = DB_u_1
password = DB_p_1

[XYZ]
host = b01        
database = DB_2

[URLList]
U1 = http://findbest.com
U2 = http://findall.com

[FPath]
filepath1 = r1.csv
# File after decrypting 
b'[ABC]\r\nhost=   a01        \r\nport = 1234\r\ndatabase = DB_1\r\nuser = DB_u_1\r\npassword = DB_p_1\r\n\r\n[XYZ]\r\nhost = b01        \r\ndatabase = DB_2\r\n\r\n[URLList]\r\nU1 = http://findbest.com\r\nU2 = http://findall.com\r\n\r\n[FPath]\r\nfilepath1 = r1.csv'

Any clue to resolve this?

Finch
  • 71
  • 1
  • 9
  • 1
    Symmetry in I/O is something to look out for. In this case you read in the plaintext using a binary mode file object, and a `bytes` object is returned. However, on decryption you output the result using the `print()` function. `print()` converts its arguments that are not strings in the same way that `str()` does. For `bytes` objects it prints them the way you see them. You can use `print()` if you apply the `decode()` method, but I think that's a mistake. You should write out the bytes object using a file object opened in `wb` mode. – President James K. Polk Mar 08 '22 at 13:35

1 Answers1

0

Solution was simple. We can just write decrypted output to some file again

with open(o_file,'wb') as f:
    f.write(decry)

Thanks for the explanation President James K. Polk

Finch
  • 71
  • 1
  • 9