The process of encrypting a file using Go is simple. Using the package we can do all the necessary steps to encrypt a file.
使用Go加密文件的过程很简单。 使用包我们可以执行所有必要的步骤来加密文件。
The first step is to open the file and read its content.
第一步是打开文件并读取其内容。
The next step is to create the block for our algorithm. This object implements the actual code so we don’t have to worry about it. In this tutorial, we are going to use AES.
下一步是为我们的算法创建块。 该对象实现了实际的代码,因此我们不必担心。 在本教程中,我们将使用AES。
The key must be 16 bytes (AES-128), 24 bytes (AES-192), or 32 bytes (AES-256), which we read from a file.
密钥必须是16字节(AES-128),24字节(AES-192)或32字节(AES-256),这些是我们从文件中读取的。
Note: Never save your key on your code.
注意 : 切勿将密钥保存在代码中。
crypto/cipher
crypto/cipher
We are going to use the GCM mode, which is a stream mode with authentication. So we don’t have to worry about the padding or doing the authentication, since it is already done by the package.
我们将使用GCM模式,这是带有身份验证的流模式。 因此,我们不必担心填充或进行身份验证,因为它已经由程序包完成了。
crypto/rand
crypto/rand
noncetag
noncetag
After this, we just need to save the ciphertext into our destination file.
之后,我们只需要将密文保存到目标文件中即可。
That’s it! You’ve encrypted a file. And the complete code:
而已! 您已加密文件。 以及完整的代码: