tar files and encrypt multiple folders in openssl in python

To tar multiple folders and encrypt them using OpenSSL in Python, you can use the following code:

main.py
import tarfile
import subprocess

# path to folders to be tarred and encrypted
folders = ['/path/to/folder1', '/path/to/folder2']

# tar file name
tar_filename = 'my_files.tar'

# create tar file
with tarfile.open(tar_filename, 'w') as tar:
    for folder in folders:
        tar.add(folder)

# encrypt tar file using openssl
password = 'my_password'.encode('utf-8')
subprocess.run(f'openssl aes-256-cbc -salt -in {tar_filename} -out {tar_filename}.enc -pass pass:{password}', shell=True)

# remove original tar file
subprocess.run(f'rm {tar_filename}', shell=True)
566 chars
21 lines

This code uses the tarfile module in Python to create a tar file containing the specified folders. Then, it uses the subprocess module to invoke OpenSSL's command-line interface to encrypt the tar file using AES 256-bit encryption with a salt and a password. Finally, the original tar file is removed for security purposes.

To decrypt the encrypted tar file using OpenSSL, you can use the following command in the command line:

main.py
openssl aes-256-cbc -d -in my_files.tar.enc -out my_files.tar -pass pass:my_password
85 chars
2 lines

This command will prompt you to enter the password you used to encrypt the file. Once the correct password is entered, the encrypted tar file will be decrypted and saved as my_files.tar.

gistlibby LogSnag