Encrypt and decrypt files with key with GPG in Linux

First, GnuPG or GPG is a tool used for data encryption. It is used via the command line and is quite easy to use.

gnugpg logo

It is recommended to compress or group multiple files instead of encrypting one by one, recommended in the case of backup copies, using zip, tar or with the format of our preference.

1. Installation

In most distributions it is found as gnupg or gnupg2.

In the case of Ubuntu and Debian, it is installed like this:

sudo apt -y install gnupg

2. Encrypt a file with key

We start with the most basic:

gpg -c filename.zip

Then it will ask us for a key twice, without this key it is practically impossible to access the file, unless it is a bad enough password that can be guessed by brute force, so like all the passwords we use this must be unique and strong, do not use it on web pages or other files.

Then a file called filename.zip.gpg will be generated. The default encryption is AES (AES-128).

2.1. Select encryption algorithm

We can select the type of encryption that will be used with the --cipher-algo option:

gpg -c --cipher-algo AES256 filename.zip

We can choose from the following types:


Keep in mind that if we use an incorrect encryption, the security of the file may be compromised, or on the contrary, there may be excessive processing just to encrypt and decrypt the file.

2.2. Different file name and alternative location

By default, the output file is saved in the same directory with the same original file name but adding the extension .gpg in the end. If we want to choose a different place to save the file or a different file name, we use --output.

gpg --output /home/user/encrypted-file.zip.gpg -c --cipher-algo AES256 filename.zip

3. Decrypt a file

We use the command directly without arguments, followed by the filename.

gpg filename.zip.gpg

It will ask us for the key we use when encrypting it.