How can I read the encryption key generated by cryptography.fernet from a yaml file as a string?

153 views Asked by At

I have a user interface in python (tkinter) that uses cryptography.fernet to encrypt the password of the user and stores it in a yaml file. For password recovery purposes, I also keep the generated encryption key in the yaml file.

My problem is the encryption key is stored with a (!!binary) prefix in the yaml file. When I want to read it back to use it for recovering the password, the yaml.load() method converts the key into a binary format which I don't want.

This is the content of credentials.yml file:

encryption_key: !!binary |
  Rkl5ZVFTQnZhNG1LcVhsSU1LV3FUZzNETGVRcWx0VTQyMzFyRDJlTWR4UT0=
username: Jack
encrypted_password: gAAAAABlXhuUZimgsD1eN7gLZpfzvxKc4Bz9fIPmVhWvwGoKkaUiSWOSf7gkFJBM8XRU-kgn37kKH3KC2XTz-CHLVX2PFerckQ==

and this is my python code:

import yaml
from cryptography.fernet import Fernet

with open("credentials.yml", 'r') as file:
    yaml_data = yaml.load(file)

print(yaml_data['encryption_key'])

The output for the code is: b'FIyeQSBva4mKqXlIMKWqTg3DLeQqltU4231rD2eMdxQ='

But I want this: Rkl5ZVFTQnZhNG1LcVhsSU1LV3FUZzNETGVRcWx0VTQyMzFyRDJlTWR4UT0=

Is there any way that I can dump the encryption key in its original format into yaml file? Or any method that converts it back to non-binary format?

2

There are 2 answers

0
Nikolaj Š. On BEST ANSWER

It's just Base64

>>> b = b'FIyeQSBva4mKqXlIMKWqTg3DLeQqltU4231rD2eMdxQ='
>>> import base64
>>> base64.b64encode(b)
b'Rkl5ZVFTQnZhNG1LcVhsSU1LV3FUZzNETGVRcWx0VTQyMzFyRDJlTWR4UT0='
2
Cow On

I'm not super familiar with YAML, but you can dump the data to string format and then process it after that. Example:

import yaml

with open("credentials.yml", 'r') as file:
    yaml_data = yaml.safe_load(file)

encryption_key = yaml.dump(yaml_data['encryption_key']).split(" ")[-1].replace("\n","")
print(encryption_key)

Result:

Rkl5ZVFTQnZhNG1LcVhsSU1LV3FUZzNETGVRcWx0VTQyMzFyRDJlTWR4UT0=

Solution 2 using base64 decoding:

import yaml
import base64

with open("credentials.yml", 'r') as file:
    yaml_data = yaml.safe_load(file)

encryption_key = base64.b64encode(yaml_data['encryption_key']).decode()
print(encryption_key)

Result:

Rkl5ZVFTQnZhNG1LcVhsSU1LV3FUZzNETGVRcWx0VTQyMzFyRDJlTWR4UT0=

credentials.yml

encryption_key: !!binary |
  Rkl5ZVFTQnZhNG1LcVhsSU1LV3FUZzNETGVRcWx0VTQyMzFyRDJlTWR4UT0=
username: Jack
encrypted_password: gAAAAABlXhuUZimgsD1eN7gLZpfzvxKc4Bz9fIPmVhWvwGoKkaUiSWOSf7gkFJBM8XRU-kgn37kKH3KC2XTz-CHLVX2PFerckQ==