tar and encrypt a folder in openssl in python

To tar and encrypt a folder in OpenSSL in Python, follow the below steps using the subprocess module:

  • Step 1: Import the required modules
main.py
import subprocess
import os
28 chars
3 lines
  • Step 2: Set the filenames and relevant paths.
main.py
folder_to_tar = 'myfolder'
tar_filename = 'myfolder.tar'
encrypted_filename = 'myfolder.tar.enc'
passphrase = b'mypassword'
cmd_tar = f'tar -cvf {tar_filename} {folder_to_tar}' # Create a tar with the folder name
cmd_encrypt = f'openssl enc -aes-256-cbc -md sha512 -in {tar_filename} -out {encrypted_filename} -pass stdin'
323 chars
7 lines
  • Step 3: Execute the system command to create a tar file of the folder.
main.py
subprocess.run(cmd_tar, check=True, shell=True) # Create a tar with the folder name
84 chars
2 lines
  • Step 4: Open the encrypted_filename in write binary mode, and encrypt the tar_filename file.
main.py
with open(encrypted_filename, 'wb') as fout:
    subprocess.run(cmd_encrypt, check=True, shell=True, input=passphrase, stdout=fout) # Encrypt the contents while writing to output file object
191 chars
3 lines
  • Step 5: Remove the tar file.
main.py
os.remove(tar_filename) # Remove tar file
42 chars
2 lines

Putting it all together in a function:

main.py
import subprocess
import os

def tar_encrypt_folder(folder_to_tar, passphrase):
    tar_filename = f'{folder_to_tar}.tar'
    encrypted_filename = f'{folder_to_tar}.tar.enc'
    cmd_tar = f'tar -cvf {tar_filename} {folder_to_tar}'
    cmd_encrypt = f'openssl enc -aes-256-cbc -md sha512 -in {tar_filename} -out {encrypted_filename} -pass stdin'

    try:
        subprocess.run(cmd_tar, check=True, shell=True)
        with open(encrypted_filename, 'wb') as fout:
            subprocess.run(cmd_encrypt, check=True, shell=True, input=passphrase, stdout=fout)
        os.remove(tar_filename)
        print(f'Folder {folder_to_tar} successfully tarred and encrypted.')
    except subprocess.CalledProcessError as e:
        print(f'Error occurred while tarring and encrypting folder {folder_to_tar}. Error message: {e}')
819 chars
18 lines

Note: Remember to pass the passphrase as a bytes object.

gistlibby LogSnag