def close(self): if not self.closed and self.mode == "w": with tempfile.SpooledTemporaryFile() as f: manifest_json = json.dumps(self.manifest) f.write(manifest_json.encode(TEXT_ENCODING)) ti = TarFile.tarinfo(self.MANIFEST_FILE) ti.size = f.tell() ti.mtime = round(time.time()) f.seek(0) self.addfile(ti, f) super(KeyTarFile, self).close()
def addencrypt(self, names, arcnames=None, archivename=None): if arcnames is None: arcnames = names if archivename is None: archivename = names[0] # Create temporary "archivename.tar.zip" with tempfile.SpooledTemporaryFile() as zfobj: with AESZipFile(zfobj, "w", compression=pyzipper.ZIP_DEFLATED, encryption=pyzipper.WZ_AES) as zf: zf.setpassword(self._aes_key_b64) # Create temporary "archivename.tar" with tempfile.SpooledTemporaryFile() as tfobj: with TarFile(fileobj=tfobj, mode="w") as tf: # Add files to "archivename.tar" for (n, an) in zip(names, arcnames): tf.add(n, arcname=an, recursive=True) # Now "archivename.tar" is completely written, # seek to beginning of file and write to "archivename.tar.zip" tfobj.seek(0) zf.writestr(archivename + ".tar", tfobj.read()) # Now "archivename.tar.zip" is completely written, # find out how large this file is by the current position using tell(), # then seek to beginning of file and addfile to the root tar ti = TarFile.tarinfo(archivename + ".tar.zip") ti.size = zfobj.tell() ti.mtime = round(time.time()) zfobj.seek(0) self.addfile(ti, zfobj) self.manifest["encrypted_files"].append(ti.name)