简体   繁体   中英

Reading python pickle data before writing it to a file

Background:

Hi. I'm currently working on a project that mainly relies on Pickles to save the state of objects I have. Here is a code snippet of two functions I've written:

from Kiosk import *                         #The main class used for the lockers
import gc                                   #Garbage Collector library. Used to get all instances of a class
import pickle                               #Library used to store variables in files.

def storeData(Lockers:Locker):
    with open('lockerData', 'wb') as File:
        pickle.dump(Lockers, File)

def readData():
    with open('lockerData', 'rb') as File:
        return pickle.load(File)

This pickle data will eventually be sent and received from a server using the Sockets library.

I've done some reading on the topic of Pickles and it seems like everyone agrees that pickles can be quite dangerous to use in some use cases as it's relatively easy to get them to execute unwanted code.

Objective:

For the above mentioned reasons I want to encrypt my pickle data in AES before writing it to the Pickle File, that way the pickle file is always encrypted even when sent and received form the server. My main problem now is, I don't know how to get the pickle data without writing it to the Pickle file first. pickle.dump() only allows me to write the pickle data to a file but doesn't allow me to get this pickle data straight away.

If I decide to do encryption after the pickle data has already been written to the file that would mean that there would be a period of time where the pickle data is stored in plain text, and I don't want that to happen.

Psudocode:

Here is how I'm expecting the task execution to flow:

PickleData = createPicle(Lockers)
PickleDataE = encrypt(PickleData)

with open('textfile.txt', 'wb') as File:
     File.write(PickleDataE) 

Question:

So my question is, how can I get the pickle data without writing it to a file?

You can store the pickle data to file as the encrypted data itself. When you read the encrypted data, you decrypt it to a variable. If you wrap that variable in an io.StringIO object, you can read it just like you do from a file, except it's in memory now. IF you give that a try, i'm sure future questions can help with how to read the decrypted data as if it were pickle data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM