Search code examples
pythonyamlpython-cryptography

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


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?


Solution

  • It's just Base64

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