I have files that I have read into memory using the following.
with open("myfile.txt", 'r') as FID:
data = FID.read()
file_data = base64.urlsafe_b64decode(data.encode('UTF-8'))
I would like to encrypt the contents of this file using 7zip and AES256. I would like it to be equivalent to when using 7zip on desktop.
For this purpose, I found py7zr.
The example that is provided for this library is as follows.
import py7zr
with py7zr.SevenZipFile('target.7z', 'w', password='secret') as archive:
archive.writeall('/path/to/base_dir', 'base')
I imagine that I could use io.StringIO. The following could be the "file" I write to.
encrypted_data = io.StringIO()
How do I go from here?
I intend to upload this as a 7zip file to Google Drive. Since the file is already in memory, I would just want to encrypt it in memory and pass it along to the below Google Drive function. As can be seen, I pass in my file as bytes in memory to upload it to Google Drive.
def GDrive_UploadFile_FromMemory(self, fileInstance, filename, parentIDs = None):
try:
filename_pathlib = pathlib.PurePath(filename)
filename_no_extension = filename_pathlib.stem
mimeType = self.GDrive_ExtensionToMime(filename)
if type(fileInstance) == str:
fileInstance = fileInstance.encode()
media = MediaIoBaseUpload(io.BytesIO(fileInstance), mimetype=mimeType, resumable=True)
body = {'name' : filename_no_extension}
if type(parentIDs) is str:
parentIDs = [parentIDs]
elif parentIDs is not None and type(parentIDs) != list():
self.GDLogger.error(f"ParentIDs [{parentIDs}] was not valid. Trying to upload {filename}")
if parentIDs is not None:
body["parents"] = parentIDs
request = self.GDrive_Service.files().create(media_body=media, body=body)
response = None
while response is None:
status, response = request.next_chunk()
if status:
self.GDLogger.info(f"Upload Status for file [{filename}] : {status.progress()*100}")
return response.get('id')
except:
self.GDLogger.error("An error has occurred in GDrive_UploadFile")
tb = traceback.format_exc()
self.GDLogger.exception(tb)
return False