I am trying to decrypt an encrypted file that is read from and stored in c_text
.
from cryptography.fernet import Fernet
def cipher_decrypt(c_text):
key = open(key_loc,'rb')
key.seek(0)
key_b = key.read()
print ('Key: ' + str(key_b))
print ('\nCipher text: ' + str(c_text))
cipher_suite = Fernet(key_b)
key.close()
plain_text = cipher_suite.decrypt(c_text).decode()
print ('\nPlain text: ' + plain_text)
return plain_text
When called, this should print the following:
Key: b'z7oCVMrxjjgx3n1HFI9oCkyxMnOrXekYKNMEBDKF704='
Cipher text: b'gAAAAABbQxMuhTmZGb0fgR6eRwQO9_qPv0tMI9GVVtyNZbHmDb6YY0veCrvG8uat5m_huC6ZHjI17V-HhLTrUGgdQGlwowY1t24cAq9ybJgfGeQVwWLsR_0=gAAAAABbQxMvgyBwq3hhMbLLP1VMbbboix4qw_TD0nF164TN2QqLGA5iHtX-dpEkj4ALMUY_dhYMqOfXY0ZUqIiX4Z_7Ud-EB8FHN0RsSiaiTBXHOS6_55A=gAAAAABbQxMwm8dek1OLeJp-sE6qmrXQSgbVqi3Sx2JwafW4YpTWuRJosBWJJpBFQ8zp8_rQ5rsLhhs7mQ4XwhGxND1GXmg8RZSrQ9-eclg6L5qyHH5Rch4='
Plain text: Servicename: gmail\n Username: gmail\n Password: gmail\n\n
However, it only prints the first line of the Plain text. What is wrong?
EDIT: Here is the snippet of the code where I write to the file, along with the encryption function.
ser_name = pymsgbox.prompt("Enter service name")
ser_name_s = 'Servicename: ' + str(ser_name) + '\n'
manager = open(mng_name,'ab')
manager.write(cipher_encrypt(ser_name_s))
manager.close()
acc_name = pymsgbox.prompt("Enter user name or email associated with " + str(ser_name))
acc_name_s = 'Username/Email: ' + str(acc_name) + '\n'
manager = open(mng_name,'ab')
manager.write(cipher_encrypt(acc_name_s))
manager.close()
pw_name = pymsgbox.password("Enter password associated with " + str(acc_name))
pw_name_s = 'Password: ' + str(pw_name) + '\n'
manager = open(mng_name,'ab')
manager.write(cipher_encrypt(pw_name_s))
manager.close()
encrypt function:
def cipher_encrypt(p_text):
key = open(key_loc,'rb')
key.seek(0)
key_b = key.read()
cipher_suite = Fernet(key_b)
key.close()
cipher_text = cipher_suite.encrypt(p_text.encode())
return cipher_text
EDIT 2: After some testing, I have noticed that the decryption is only taking place for the first write command in the above code (even though the encryption is taking place normally). So there is definitely an issue with that, though I can't for the life of me figure it out...