DEV Community

Cover image for Encrypt File in Ubuntu with GPG
HostnExtra Technologies
HostnExtra Technologies

Posted on

Encrypt File in Ubuntu with GPG

In this article, we'll explain how to encrypt file in Ubuntu with GPG.

“GPG” or “GNU Privacy Guard” allows you to securely encrypt files and data with a strong encryption algorithm. GPG is an excellent method to ensure secure communication between two parties. It allows sensitive information to be easily shared across an insecure network.

Prerequisites

  • An Ubuntu installed desktop, dedicated server or KVM VPS.
  • A root user access or normal user with administrative privileges to install GPG.

Encrypt File in Ubuntu with GPG

Install GPG in Ubuntu

We can install GPG using following command:

# apt install gpg

Encrypt file using GPG

Following command will encrypt test.txt.

# gpg -c test.txt

Once you run the above command, you will ask to enter a passphrase that will be used for encrypting and decrypting the file.

Encrypt file in Linux

After you enter passphrase, file gets encrypted and one file gets create in the following format:

test.txt.gpg

To decrypt the file, run a command in the following format:

# gpg test.txt.gpg

Use the passphrase you initially used to encrypt the file. Once decrypted, you will get back a “test.txt” file.

Generate a GPG key pair

You can use a pair of “public” and “private” keys to encrypt and decrypt files. To generate a GPG key pair, you can use the command below:

# gpg --generate-key

Follow the instructions and enter a username and password when prompted. After generating the key pair, GPG will show the generated public key in terminal output.

To export public key to a file, run the following command:

# gpg --armor --export --output "public_key"

Replace “public_key” with your own public key generated in the step above. Your generated private keys will be available in “$HOME/.gnupg/” directory.

Encrypt a file using public key of someone else, use the following command:

# gpg --encrypt --recipient-file public_key.file test.txt

Note: Replace public_key.file with public key of the person you want to send the file.

Decrypt a file that was encrypted using your public key, use the following command:

# gpg --decrypt --output test.txt test.txt.gpg

GPG will automatically detect your private keys during decryption as long as they are stored in the “$HOME/.gnupg/” directory.

Learn more about GPG cheatsheet.

In this article, we have seen how to encrypt file in Ubuntu with GPG.

Top comments (0)