Home > database >  Convert a Bytes String to Dictionary in Python
Convert a Bytes String to Dictionary in Python

Time:01-12

Basic Information

I am creating a python script that can encrypt and decrypt a file with previous session data.

The Problem

I am able to decrypt my file and read it using a key. This returns a bytes string which I can in turn convert to a string. However, this string needs to be converted to a dictionary, which I cannot do. Using ast, json and eval I have run into errors.

Bytes string

decrypted = fernet.decrypt(encrypted)

String

string = decrypted.decode("UTF-8").replace("'", '"')

If I use eval() or ast.literal_eval() I get the following error:

error_1

Then I tried using json.loads() and I get the following error:

enter image description here

The information blocked out on both images is to protect my SSH connections. In the first image it is giving me a SyntaxError at the last digit of my ip address.

The Function

The function that is responsible for this when called looks like this:

def FileDecryption():
    with open('enc_key.key', 'rb') as filekey:
        key = filekey.read()
        filekey.close()

    fernet = Fernet(key)

    with open('saved_data.txt', 'rb') as enc_file:
        encrypted = enc_file.read()
        enc_file.close()

    decrypted = fernet.decrypt(encrypted)
    print(decrypted)

    string = decrypted.decode("UTF-8").replace("'", '"')

    data = f'{string}'

    print(data)

    #data = eval(data)
    data = json.loads(data)
    print(type(data))

    for key in data:
        #command_string = ["load", data[key][1], data[key][2], data[key][3], data[key][4]]
        #SSH.CreateSSH(command_string)
        print(key)

Any help would be appreciated. Thanks!

CodePudding user response:

Your data seems like it was written incorrectly in the first place, but without a complete example hard to say.

Here's a complete example that round-trips a JSON-able data object.

# requirement:
#   pip install cryptography
from cryptography.fernet import Fernet
import json

def encrypt(data, data_filename, key_filename):
    key = Fernet.generate_key()
    with open(key_filename, 'wb') as file:
        file.write(key)

    fernet = Fernet(key)
    encrypted = fernet.encrypt(json.dumps(data).encode())
    with open(data_filename, 'wb') as file:
        file.write(encrypted)

def decrypt(data_filename, key_filename):
    with open(key_filename, 'rb') as file:
        key = file.read()

    fernet = Fernet(key)
    with open(data_filename, 'rb') as file:
        return json.loads(fernet.decrypt(file.read()))

data = {'key1': 'value1', 'key2': 'value2'}
encrypt(data, 'saved_data.txt', 'enc_key.key')
decrypted = decrypt('saved_data.txt', 'enc_key.key')
print(decrypted)

Output:

{'key1': 'value1', 'key2': 'value2'}
  • Related