我使用这里给出的说明和代码创建了一对*.pub和*.sec文件:
https://www.gnupg.org/documentation/manuals/gnupg/Unattended-GPG-key-generation.html
(我正在使用此文档,因为我想到的最终应用程序是自动加密/解密管道.)
Q1:如何使用gpg2和*.pub文件加密另一个文件?
Q2:如何使用gpg2和协同工具*.sec解密使用配套*.pub文件加密的文件?
重要提示: 我只对那些适合无监督操作的程序化实现的答案感兴趣.请不要发布只能以交互方式进行的答案.我对可以在Python中实现的解决方案特别感兴趣.
请提供相关文档的精确指示.
关于你所说的一些信息:
我使用说明创建了一对*.pub和*.sec文件
完美地与您正在交换信息的人共享公钥,但从技术上讲,当您以编程方式工作时,您不需要直接使用这些文件.
需要注意的是:
实际上,我对这个问题有点困惑.我读过相互矛盾的信息[...]
我同意这很令人困惑.在这种情况下,我认为最好使用版本1,因为它有更多的经验,并且您可以找到第三方库使用.
在这个答案中,我试过:
使用第一个库,您只需将其安装在您的系统中:
sudo pip install python-gnupg
Run Code Online (Sandbox Code Playgroud)
然后编写一个Python脚本来执行所需的所有操作.
我写了一个简单的回答你的问题.
#!/bin/python
import gnupg
GPG_DIR='/home/bsquare/.gnupg'
FILE_TO_ENCRYPT='/tmp/myFileToEncrypt'
ENCRYPTED_FILE='/tmp/encryptedFile'
DECRYPTED_FILE='/tmp/decryptedFile'
SENDER_USER='Bsquare'
TARGET_USER='Kjo'
gpg = gnupg.GPG(gnupghome=GPG_DIR)
print("Listing keys ...")
print(gpg.list_keys())
# On SENDER_USER side ... encrypt the file for TARGET_USER, with his public key (would match the kjo.pub if the key was exported).
print("Encrypting file " + FILE_TO_ENCRYPT + " for " + TARGET_USER + " ...")
with open(FILE_TO_ENCRYPT, "rb") as sourceFile:
encrypted_ascii_data = gpg.encrypt_file(sourceFile, TARGET_USER)
# print(encrypted_ascii_data)
with open(ENCRYPTED_FILE, "w+") as targetFile:
print("encrypted_ascii_data", targetFile)
# On TARGET_USER side ... decrypt the file with his private key (would match the kjo.sec if the key was exported).
print("Decrypting file " + ENCRYPTED_FILE + " for " + TARGET_USER + " ...")
with open(ENCRYPTED_FILE, "rb") as sourceFile:
decrypted_ascii_data = gpg.decrypt_file(sourceFile)
# print(decrypted_ascii_data)
with open(DECRYPTED_FILE, "w+") as targetFile:
print(decrypted_ascii_data, targetFile)
Run Code Online (Sandbox Code Playgroud)
需要注意的是,我的密钥环包含我的Bsquare用户的pub/sec对,以及用户的pub密钥Kjo.