手把手指导：在 Linux 上使用 GPG 加解密文件
GPG 加密
![](/data/attachment/album/202112/15/133531wcs1iy4luihr3beg.jpg)


[GnuPG](https://gnupg.org/)，俗称 GPG，是一个非常通用的工具，被广泛用作电子邮件、信息、文件或任何你需要安全地发送给别人的东西的加密行业标准。


学习使用 GPG 很容易，你可以在几分钟内就学会使用它。


在本教程中，我将告诉你如何用 GPG 加密和解密文件。这是一个简单的教程，你可以在你的 Linux 系统上尝试所有的练习。这将帮助你练习 GPG 命令，并在你完全陌生的情况下理解它。


请先阅读整个教程，然后开始自己做。


### GPG 是如何进行加密的？


![GPG 加密](/data/attachment/album/202112/15/133645b1i73az322l66l57.png)


要使用 GPG，你首先需要有一个 GPG 密钥。


GPG 密钥是你在后面的教程中用来加密（或解密）文件的东西。它也是用来识别你的身份的，你的名字和电子邮件也会与密钥绑定。


GPG 密钥的工作原理是使用两个文件，一个私钥和一个公钥。这两个密钥是相互联系的，并且 GPG 的所有功能都需要使用它们，特别是对文件加密和解密。


当你用 GPG 加密一个文件时，它使用的是私钥。然后，这个新的加密文件**只能**用配对的公钥进行解密。


私钥，顾名思义，是以私下的、不给任何人看的方式来存储的密钥。


另一方面，公钥是用来给其他人的，或者你希望能够解密你的文件的任何人。


这就是 GPG 的加密方法的主要作用。它允许你对文件进行本地加密，然后允许其他人确保他们收到的文件实际上是由你发送的。因为他们能够解密文件的唯一方法是使用你的公钥，而这只有在文件首先使用你的私钥加密的情况下才有效。


**反之**，其他人可以用你的公钥对文件进行加密，而唯一能够解密的方法是用你的私钥。因此，允许其他人公开发布文件，而不用担心除了你以外的人能够阅读它们。（LCTT 译注：另外一个常见的用例是你用你的私钥对公开发布的文件进行签名，别人使用你的公钥通过验证你的签名而确信文件是你发布的、并没有被篡改。但本文没有涉及这个用例。）


换句话说，如果一个文件是用私钥加密的，它只能用相应的公钥解密。而如果一个文件是用公钥加密的，它只能用相应的私钥解密。


#### 你已经在使用 GPG 而没有意识到


一个最常见的使用 GPG 的例子是在 Linux 软件包管理器中，特别是 [外部仓库](https://itsfoss.com/adding-external-repositories-ubuntu/)。你把开发者的公钥添加到你系统的可信密钥中。开发者用他/她的私钥签署软件包（生成签名）。由于你的 Linux 系统拥有该公钥文件，它就能理解该软件包实际上是来自受信任的开发者。


许多加密服务在你没有意识到的情况下使用了某种 GPG 的实现。但现在最好不要去研究这些细节。


现在你对这个概念有点熟悉了，让我们看看如何使用 GPG 来加密一个文件，然后用它来解密。


### 用 GPG 对文件进行加密和解密


![](/data/attachment/album/202112/15/133646o30ren9lnfnn6jyn.png)


这是一个非常简单的场景。我假定你只有一个系统，你想看看 GPG 是如何工作的。你并没有把文件发送到其他系统。你对文件进行加密，然后在同一个系统上解密。


当然，这不是一个实际的用例，但这也不是本教程的目的。我的目的是让你熟悉 GPG 命令和功能。之后，你可以在现实世界中使用这些知识（如果需要的话）。为此，我将告诉你如何与他人分享你的公钥。


#### 第一步：安装 GPG


GPG 可以在大多数发行版的软件库中找到，开箱即用。


在基于 Debian 和 Ubuntu 的系统中，安装 `gpg` 包：



```
sudo apt install gpg

```

如果你使用 [基于 Arch 的发行版](https://itsfoss.com/arch-based-linux-distros/)，用 [pacman 命令](https://itsfoss.com/pacman-command/) 安装 `gnupg` 软件包：



```
sudo pacman -S gnupg

```

#### 第二步：生成一个 GPG 密钥


在你的系统上生成一个 GPG 密钥只需要一条简单的命令。


只要运行下面的命令，就会生成你的密钥（你可以对大多数问题使用默认值，如下面的下划线部分所示）。



```
gpg --full-generate-key

```

![生成 GPG 密钥](/data/attachment/album/202112/15/133646o4vmvoddrpo4mm4b.png)


**检查 GPG 密钥**


然后你可以通过使用 `--list-secret-keys` 和 `--list-public-keys` 参数，分别看到私钥和公钥都是通过 `pub` 下显示的那个 ID 相互绑定的。


![列出 GPG 密钥](/data/attachment/album/202112/15/133646hkm9czc4wl3l19zk.png)


#### 第三步：用 GPG 加密一个文件


现在你已经设置了 GPG 密钥，你可以开始对我们的文件进行加密了。


使用下面的命令来加密文件：



```
gpg --encrypt --output file.gpg --recipient user@example.com file

```

让我们快速浏览一下该命令的内容：


首先，你指定了 `—encrypt` 选项。这告诉 GPG，我们将对一个文件进行加密。


接下来，你指定了 `--output file.gpg`。这可以是任何名字，不过惯例是给你要加密的文件的名称加上 `.gpg` 扩展名（所以 `message.txt` 会变成 `message.txt.gpg`）。


接下来，你输入 `—recipient user@example.com`。这指定了一个相应的 GPG 密钥的电子邮件，这个密钥实际上在这个系统上还不存在。


有点迷惑？


工作原理是，你在这里指定的电子邮件必须与你本地系统中的公钥相联系。


通常情况下，这将是来自另外一个人的 GPG 公钥，你要用它来加密你的文件。之后，该文件将只能用该用户的私钥进行解密。


在这个例子中，我将使用我以前的与 `user@example.com` 关联的 GPG 密钥。因此，其逻辑是，我用 `user@example.com` 的 *公钥* 对文件进行加密，然后只能用 `user@example.com` 的 *私钥* 进行解密。


如果你是为别人加密文件，你只有该公钥，但由于你是为自己加密文件，你的系统上有这两个密钥。


最后，你只需指定你要加密的文件。在这个例子中，让我们使用一个名为 `message.txt` 的文件，内容如下：



```
We're encrypting with GPG!

```

![文本文件样本](/data/attachment/album/202112/15/133647pd2yesr9y9kdqynm.png)


同样地，如果电子邮件是 `user@example.com`，新的 GPG 命令将如下所示：



```
gpg --encrypt --output message.txt.gpg --recipient user@example.com message.txt

```

![用 GPG 加密文件](/data/attachment/album/202112/15/133647gsnxq3nsgnsq3s3y.png)


如果你尝试阅读该文件，你会看到它看起来像乱码。这是预料之中的，因为该文件现在已经被加密了。


![读取加密文件会产生乱码](/data/attachment/album/202112/15/133647tjsiiijpfwpujiz1.png)


现在让我们删除未加密的 `message.txt` 文件，这样你就可以看到 `message.txt.gpg` 文件实际上在没有原始文件的情况下也能正常解密。


![](/data/attachment/album/202112/15/133647rjkcbjc5byj79cky.png)


#### 第四步：用 GPG 解密加密的文件


最后，让我们来实际解密加密的信息。你可以用下面的命令来做。



```
gpg --decrypt --output file file.gpg

```

通过这里的参数，我们首先指定 `—decrypt`，它告诉 GPG 你将会解密一个文件。


接下来，你输入 `—output` 文件，这只是告诉 GPG，在你解密后，你将把我们文件的解密形式保存到哪个文件。


最后，你输入 `file.gpg`，这是你的加密文件的路径。


按照这个例子，我使用的命令是这样的。



```
gpg --decrypt --output message.txt message.txt.gpg

```

![用GPG解密文件](/data/attachment/album/202112/15/133647z7tv3726ko9to9oq.png)


然后就完成了！当你想用 GPG 加密和解密文件时，这就是全部内容了。


剩下你可能想知道的是如何与他人分享你的公钥，以便他们在将文件发送给你之前对其进行加密。


### 发送和接收 GPG 密钥


要给别人发送一个 GPG 密钥，你首先需要从你的**钥匙链**中导出它，它包含了你所有的公钥和私钥。


要导出一个密钥，只需在你的钥匙链中找到密钥的 ID，然后运行以下命令，用密钥的 ID 替换 `id`，用你想保存的文件名替换 `key.gpg`。



```
gpg --output key.gpg --export id

```

![导出 GPG 公钥](/data/attachment/album/202112/15/133648q99nhi98a9ib8c91.png)


要导入一个密钥，只需把输出文件（来自前面的命令）给其他用户，然后让他们运行下面的命令。



```
gpg --import key.gpg

```

![](/data/attachment/album/202112/15/133648g7dubcrr3yfcocmu.png)


但要正常使用该密钥，你需要验证该密钥，以便 GPG 正确地信任它。


这可以通过在其他用户的系统上使用 `--edit-key` 参数来完成，然后对密钥进行签名。


首先运行 `gpg --edit-key id`：


![GPG 编辑密钥](/data/attachment/album/202112/15/133648vt6ucccq3tjdceuv.png)


接下来，使用 `—fpr` 参数，它将显示密钥的指纹。这个命令的输出应该与你自己机器上的输出进行验证，这可以通过在你的系统上运行同样的 `--edit-key` 参数来找到。


![GPG 密钥的指纹](/data/attachment/album/202112/15/133648bxss6p16zbssppg6.png)


如果一切吻合，只需使用 `—sign` 参数，一切就可以开始了。


![签署 GPG 密钥](/data/attachment/album/202112/15/133649hi1pv42s2iv2avsj.png)


就是这样！其他用户现在可以开始用你的公钥加密文件了，就像你之前做的那样，这可以确保它们只有在你用你的私钥解密时才能被你读取。


这就是使用 GPG 的所有基础知识！


### 总结


现在你已经了解了开始使用 GPG 所需要的一切，包括为自己和他人加密文件。正如我前面提到的，这只是为了了解 GPG 的加密和解密过程是如何工作的。你刚刚获得的基本 GPG 知识在应用于真实世界的场景中时可以更上一层楼。


还需要一些帮助来弄清楚一些东西，或者有一些不工作的东西？欢迎在下面的评论中留下任何内容。




---


via: <https://itsfoss.com/gpg-encrypt-files-basic/>


作者：[Hunter Wittenborn](https://itsfoss.com/author/hunter/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[wxy](https://github.com/wxy) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
![Warp Terminal](/assets/images/warp-terminal.webp)


![Warp Terminal](/assets/images/warp-terminal.webp)

[GnuPG](https://gnupg.org/?ref=itsfoss.com), popularly known as GPG, is an extremely versatile tool, being widely used as the industry standard for encryption of things like emails, messages, files, or just anything you need to send to someone securely.

It’s easy to get started with GPG, and you can be on your way with using it in a matter of minutes.

In this tutorial, I’ll show you how to encrypt and decrypt files with GPG.


*This is a simple tutorial, and you may try all of it to practice on your Linux system as well. This will help you practice the GPG commands and understand it when you are absolutely new to it.*Read the entire tutorial first and then start doing it on your own.

## What are GPG Keys?

To start using GPG, you’ll first need to have a GPG key.

A GPG key is what you’ll use to encrypt (or decrypt) files later in the tutorial. It’s also what is used to identity you, with things like your name and email being tied to the key as well.

GPG keys work by using two files, a private key and a public key. These two keys are tied to each other, and are both needed to use all of GPG’s functionality, notably encrypting and decrypting files.

The private key is meant to be stored in a fashion stated directly in its name – privately, and not given out to anyone.

The public key, on the other hand, is meant to be given to others, or anyone you want to be able to communicate with.

### How GPG Encryption Work?

As said above, GPG encryption utilizes both the public and private keys, an asymmetric encryption technique. It allows you to encrypt files locally and then allows others to be ensured that the files they received were actually sent from you.

When you intend to encrypt a file using GPG, you will use the **Public key** of the person to whom you intend to send the file. Then, the receiver can decrypt that file using his private key. Let us go in a bit of detail.

You now know that GPG works with the public-private key pair. While you create a key on your system, it generates the public and private key. When a file is encrypted using your public key, only your associated private key can decrypt it. Not even your Public key, the one used to encrypt that file, can decrypt it.

So, let’s say a person called *Sender *wants to encrypt a file and send it to another person called *Receiver*.

*Sender*will ask the*Receiver*to send his public key to him.- Receiver will send his public key to the Sender. This can be either by email or through any public key server like
[https://keyserver.ubuntu.com/](https://keyserver.ubuntu.com/) - When
*Sender*gets the public key of the*Receiver*, he/she encrypts the file that needs to be transmitted with the Receiver’s public key. - The file is now transmitted to the Receiver.
- Once
*Receiver*gets the encrypted file, he/she will decrypt the file using his/her Private Key. This is possible because the file was encrypted using the*Receiver’s*public key. - Thus, the communication is completed securely, without any other person decrypting the message.

Here's an illustration to describe the process:

Encrypt and Decrypt Files using GPG Keys

### Why You Should Never Encrypt Files with your Private Key?

You should NEVER encrypt a file using your private key. This is because, if you encrypt the file using your private key, then the only key that can decrypt that file is your public key. As the name suggests, a Public key is meant to be shared with others or added to public key servers. Thus, in essence, anybody, who has access to your public key, can decrypt your data.

This is not acceptable, since you encrypt a file only to be decrypted by the receiver, and that’s the point of encryption in the first place.

### You are already using GPG without realizing

One of the most common examples of using GPG is in the Linux package manager, specially the [external repositories](https://itsfoss.com/adding-external-repositories-ubuntu/). You add the public key of the developer into your system’s trusted keys. The developer signs the packages (generates a signature) with his/her private key. Since your Linux system has the public file, it understands that the package is actually coming from the trusted developer.

A number of encrypted services use some sort of GPG implementation underneath without you realizing it. But it’s better to not go into those details right now.

Now that you are a bit familiar with the concept, let’s see how you can use GPG for encrypting a file and then use it to decrypt.

## Encrypting and decrypting files with GPG

![](https://itsfoss.com/content/images/2024/02/GPG-encryption-basic.webp)

This is a very simplistic scenario. Here, we presume that, you have two systems, with public-private key pairs. You want to encrypt a file and then decrypt on the other system.

### Step 1: Installing GPG

Firstly, you need to install GPG on both systems. GPG can be found in most distribution’s repositories out of the box.

On Debian and Ubuntu-based systems, install the gpg package:

`sudo apt install gpg`


If you use [Arch-based distributions](https://itsfoss.com/arch-based-linux-distros/), install the gnupg package with the [pacman command](https://itsfoss.com/pacman-command/):

`sudo pacman -S gnupg`


### Step 2: Generating a GPG key

Generating a GPG key on your system is a simple one-command procedure.

Just run the following command, and your key will be generated. You can use the defaults for most questions as shown below.

`gpg --full-generate-key`


![GPG Key Generation on a system](https://itsfoss.com/content/images/2024/02/gpg-key-generation.webp)

**Checking the GPG Key**

You can then see that the private key and public key are both tied to each other by that ID shown under **pub** by using the **–list-secret-keys** and **–list-public-keys** commands respectively:

![Lisiting Public and Private keys on a system](https://itsfoss.com/content/images/2024/02/gpg-list-secret-keys.webp)

You should do this on both the systems you want to communicate with.

### Step 3: Receiving the Public Key of the Receiver

To encrypt the file, you need the Public key of the receiver. So, for simplicity, the receiver can send his public key as a text file to you.

For this, the receiver should export his public key to an ASCII armored format. You can use the command below.

`gpg --output sample.gpg --export --armor `[[email protected]](/cdn-cgi/l/email-protection)


Here,

is the email address used for the key pair of the receiver.[[email protected]](/cdn-cgi/l/email-protection)

It will create an ASCII armored file called *sample.gpg* (with the `--armor`

option)*,* which is easier to send to other people.

Now, the receiver can send the file to the sender using email, or other means.

### Step 4: Import the Public key of the Receiver

Once you receive the public key of the receiver, you should import it to your system. This is to make sure that, the key is accessible, and you can encrypt data using that key.

To import the key, go to the directory where you downloaded the file and just run:

`gpg --import sample.gpg`


![Public key of the receiver is imported on the sender's end](https://itsfoss.com/content/images/2024/02/receiver-end-public-key-imported.png)

### Step 4: Verify the Fingerprint of the Key

Are you sure the key you got is from the right person you want to communicate with? What if it was a wrong key so that you encrypted the data, only to be decrypted by an unexpected person? To avoid this, you should make sure that the key you got is from the person that you aim to communicate with.

GPG Fingerprint is used to verify the authenticity of the key. Once you receive the key, first, list the keys:

`gpg --list-keys`


![Listing keys at the sender’s end](https://itsfoss.com/content/images/2024/02/listing-keys-at-sender-end.png)

Now, from the list of public keys, note the one that is from the receiver. To start to verify the key, run the gpg command with the `--edit-key`

option on the sender’s system.

`gpg --edit-key `[[email protected]](/cdn-cgi/l/email-protection)


This will enter you into a `command>`

prompt. Here, run the `fpr`

command, which will show the fingerprint for the key.

`fpr`


It will print a fingerprint of the key. This should be validated against the output on the other machine (sender and receiver), which can be found by running the same ** --edit-key** command on that system.

You can verify it by calling the sender or by some other authentic means to verify the identity of the receiver.

Once you found the fingerprint are matching, on the same command prompt, enter:

`sign`


It will ask you to confirm with a passphrase. Do it and you are ok to go. You can exit the prompt using CTRL+D. Press `y`

to save changes and exit.

![Verify the authenticity of the public key](https://itsfoss.com/content/images/2024/02/checking-authenticity-of-key.png)

### Step 5: Encrypt the File

Now that you’ve set up the GPG keys, you can start encrypting our files! Let’s say `document.txt`

is the name of or file, that needs to be encrypted.

Use the following command to encrypt files:

`gpg --output document.txt.gpg --encrypt --recipient `[[email protected]](/cdn-cgi/l/email-protection) document.txt


Let’s go over what that command does very quick:

First, you specified ** --output file.gpg**. This can be anything, though it’s typically the name of the file you’re encrypting plus a

**.gpg**extension (so

**document.txt**would become

**document.txt.gpg**).

Then, you specified the ** --encrypt** option. This tells GPG that we’ll be encrypting a file.

Next, you type ** --recipient **. This specifies the email for a corresponding GPG key of the receiver, that you have received and imported earlier.

[[email protected]](/cdn-cgi/l/email-protection)

![Encrypting the Document on the Sender’s end](https://itsfoss.com/content/images/2024/02/encrypting-the-document.png)

When you try to view the content of this encrypted file, it will be some gibberish.

![Gibberish result, when the encrypted data is read using common tools](https://itsfoss.com/content/images/2024/02/reading-the-encrypted-file-results-gibberish.png)

### Step 6: Send the Encrypted File

You can now send this file to the recipient through any means. Only the receiver, with his Private key can now decrypt this message.

### Step 7: Decrypt the Message

On the receiver’s end, you have `document.txt.gpg`

file, which is the encrypted file. To decrypt that file, you will run:

`gpg --output document.txt --decrypt document.txt.gpg`


![Decrypting the document on the receiver’s end](https://itsfoss.com/content/images/2024/02/decrypt-on-receiver-end.png)

Going through the argument here, we first enter ** --output** file, which tells GPG what file you’ll be saving the encrypted form of our file to after you decrypt it.

Then, we specify the option ** --decrypt**, which tells GPG that you’re going to be decrypting a file.

Lastly, you enter ** file.gpg**, which is just the path to your encrypted file.

What this means is, you are decrypting the ** document.txt.gpg** file to the original


`document.txt`

**. It will ask for the password, that the receiver has set. Give it and you are done!**

*using the private key of the receiver*If you try to decrypt the document on the sender’s end itself, then you will get an error:

![Error when trying to decrypt the file on the sender’s end](https://itsfoss.com/content/images/2024/02/trying-to-decrypt-on-the-senders-end.png)

This is because the file was encrypted using the Receiver’s public key. So the only key, that can decrypt this data is the Receiver’s private key.

### Encrypting and Decrypting for Self

If you want to encrypt and decrypt for yourself, you can do that as well. First, encrypt a file using:

`gpg --output document.txt.gpg --encrypt --recipient `[[email protected]](/cdn-cgi/l/email-protection) document.txt


Here, the

is the email address corresponding to the gpg key of your system. Now, to decrypt the same, you can use:[[email protected]](/cdn-cgi/l/email-protection)

`gpg --output document.txt --decrypt document.txt.gpg`


This will ask for the passphrase. Give it and you are done.

## Wrapping Up

You’ve now gone over everything you need to start using GPG. As I mentioned earlier, this is just for understanding how the GPG encryption and decryption process works. The basic GPG knowledge you just acquired can be taken to the next level when applied in real-world scenarios.

*Need some help figuring out something still, or something just not working right? You are welcome to leave any of it in the comments below.*