tar and encrypt a list of folders in openssl in python

Here's an example of how to tar and encrypt a list of folders using OpenSSL in Python:

main.py
import tarfile
import subprocess

folders_to_tar = ['/path/to/folder1', '/path/to/folder2']
output_tar_file = '/path/to/output.tar'

# Create tar archive of folders
with tarfile.open(output_tar_file, "w") as tar:
    for folder in folders_to_tar:
        tar.add(folder)

# Encrypt tar archive using openssl
password = "supersecurepassword"
command = f"echo {password} |openssl enc -aes-256-cbc -pbkdf2 -iter 100000 -salt -in {output_tar_file} -out {output_tar_file}.enc"
subprocess.run(command, shell=True)
508 chars
16 lines

Explanation:

  1. First, we define a list of folders that we want to include in the tar archive, as well as the filename for the output tar archive.
  2. Next, we use the tarfile module to create a new tar archive named output_tar_file and add each folder in folders_to_tar to the archive.
  3. Finally, we use the subprocess module to run the openssl command to encrypt the tar archive using the aes-256-cbc cipher with a pbkdf2 key derivation function, 100,000 iterations, and a salt. We also pass in the password variable as input to the echo command to avoid having to type the password manually. The encrypted tar archive is saved with a filename of output_tar_file.enc.

gistlibby LogSnag