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?