The following command encrypts and compresses the files file1
, file2
and file3
:
7z a -p -mhe=on destination.7z file1 file2 file3
The archive can be uncompressed with the following command:
7z x destination.7z
Note that you may need to install 7zip (for example p7zip) with a command like:
sudo apt install p7zip
To compress and encrypt files on Linux from the command line, you can also use a combination of tools like tar
, gzip
, bzip2
, or xz
for compression, and gpg
for encryption. Here's a step-by-step guide:
tar
and gzip
(or bzip2
/xz
) with gpg
:To create a compressed archive of a directory or file, you can use tar
combined with gzip
(for .tar.gz
), bzip2
(for .tar.bz2
), or xz
(for .tar.xz
).
# Using gzip
tar -czf archive.tar.gz /path/to/directory_or_file
# Using bzip2
tar -cjf archive.tar.bz2 /path/to/directory_or_file
# Using xz
tar -cJf archive.tar.xz /path/to/directory_or_file
After compressing the files, you can encrypt the resulting archive using gpg
.
# Symmetric encryption with a passphrase
gpg -c archive.tar.gz
The -c
option tells gpg
to use symmetric encryption, which will prompt you to enter a passphrase. This command will create a file named archive.tar.gz.gpg
.
Optionally, you can remove the unencrypted archive to keep only the encrypted version.
rm archive.tar.gz
You can also combine these steps using a pipe, compressing and encrypting in a single command:
tar -czf - /path/to/directory_or_file | gpg -c -o archive.tar.gz.gpg
To decrypt and extract the contents of the encrypted archive, use the following commands:
gpg -o decrypted_archive.tar.gz -d archive.tar.gz.gpg
# Using gzip
tar -xzf decrypted_archive.tar.gz
# Using bzip2
tar -xjf decrypted_archive.tar.bz2
# Using xz
tar -xJf decrypted_archive.tar.xz
This approach provides a secure way to compress and encrypt files on Linux using built-in tools.