How to Compress and Encrypt Directory with OpenSSL on Ubuntu
This article provides a step-by-step guide on securing sensitive data in Ubuntu by combining compression and encryption. You will learn how to use tar and OpenSSL to create a protected archive and how to restore the original files securely. This process ensures your data takes up less space while remaining inaccessible to unauthorized users without the correct password.
Prerequisites
Ensure you have OpenSSL installed on your Ubuntu system. It is
typically pre-installed, but you can verify this by running
openssl version in your terminal. If it is not installed,
use sudo apt install openssl.
Compress and Encrypt the Directory
To compress a folder and encrypt it in a single step, use the
following command. Replace ./my_folder with the path to the
directory you want to secure and backup.tar.gz.enc with
your desired output filename.
tar czf - ./my_folder | openssl enc -aes-256-cbc -salt -pbkdf2 -out backup.tar.gz.encWhen you execute this command, you will be prompted to enter a
password. This password is required to decrypt the file later. Choose a
strong password and store it safely. The tar command
compresses the directory, and the pipe | sends the output
directly to openssl for encryption using the AES-256-CBC
cipher.
Decrypt and Decompress the Directory
To retrieve your original files, you need to decrypt the archive and extract the contents. Run the following command in the terminal:
openssl enc -aes-256-cbc -d -salt -pbkdf2 -in backup.tar.gz.enc | tar xzf -You will be prompted to enter the password you set during the encryption process. Once verified, the data will be decrypted and extracted into the current directory. Ensure you have sufficient disk space for the extracted files before running this command.
Verify and Clean Up
After decryption, check the extracted folder to ensure all files are
intact. If you no longer need the encrypted archive and wish to save
space, you can remove it using rm backup.tar.gz.enc. Always
keep a backup of your encrypted data before deleting the original or the
archive to prevent accidental data loss.