使用密码加密和解密文件

Encrypt and decrypt files with password

我正在使用 linux,我基本上想使用密码加密文件。

我试过使用 gpg -c myfile 进行加密,效果很好,它要求我输入密码并对其进行加密。但它只在加密时要求输入密码。

我想要一种加密文件的方法,如果你想解密它,你必须提供与加密文件相同的密码。


如果有一个 python 库也可以工作,因为我可以将它放在脚本中。

在 Linux.

下,有多种方法可以创建受密码保护的文件

GnuPG

GnuPG 可用于加密数据和创建数字签名。

要加密和解密 data.txt 文件,使用 gpg 命令如下:

$ gpg -c data.txt
$ gpg data.txt.gpg

mcrypt

mcrypt 允许您创建与 GnuPG 类似的受密码保护的文件

要加密和解密 data.txt 文件,请使用 mcrypt 命令如下:

$ mcrypt data.txt
$ mcrypt -d data.txt.nc

OpenSSL

OpenSSL Cryptography Toolkit 也可用于加密和解密文件和消息。

要加密和解密data.txt文件,使用openssl命令如下:

$ openssl enc -aes-256-cbc -salt -in data.txt -out data.txt.enc
$ openssl enc -aes-256-cbc -d -in data.txt.enc -out data.txt

那是因为 gpg-agent,一个管理私钥并用作 gpg 后端的守护进程。默认情况下,它会将您的密码缓存一段时间。您可以使用以下选项(来自 man gpg-agent)进行配置:

--default-cache-ttl n
              Set the time a cache entry is valid to n seconds.  The default is 600 seconds.  Each time a cache entry is accessed, the entry's timer is reset.  To set an entry's maximum
              lifetime,  use  max-cache-ttl.   Note that a cached passphrase may not evicted immediately from memory if no client requests a cache operation.  This is due to an internal
              housekeeping function which is only run every few seconds.

--max-cache-ttl n
              Set  the  maximum time a cache entry is valid to n seconds.  After this time a cache entry will be expired even if it has been accessed recently or has been set using gpg-
              preset-passphrase.  The default is 2 hours (7200 seconds).

清除缓存的一种方法是重新加载 gpg-agent:gpgconf --reload gpg-agent

您可以使用 gpg -c myfile && gpgconf --reload gpg-agent 来加密您的文件,之后如果您尝试使用 gpg myfile.gpg

来解密它,将会询问密码