python gnupg.encrypt : no errors but not encrypting data or files

柔情痞子 提交于 2019-12-01 18:03:46

Okay, I finally got around to looking at this and got basic encryption to work from the command line. Here's an example that will work to encrypt data entered from the command line:

import gnupg

gpg_home = "/path/to/gnupg/home"
gpg = gnupg.GPG(gnupghome=gpg_home)

data = raw_input("Enter data to encrypt: ")
rkey = raw_input("Enter recipient's key ID: ")

encrypted_ascii_data = gpg.encrypt(data, rkey)

print(encrypted_ascii_data)

Change the gpg_home to whichever of those two GnuPG paths you want to use. The first one looks like the default installation location and the second one appears to be specific to your user account. The script will prompt for some text to encrypt and a key ID to encrypt to, then print the ASCII armoured encrypted data to stdout.

EDIT: I'm not certain, but I suspect the reason your code failed was either due to using the whole fingerprint for the recipient key ID, which is unnecessary (I used the 0xLONG format, an example of which is on my profile), or you called the wrong GPG home directory.

EDIT 2: This works to encrypt files and writes the output to a file in the same directory, it will work as is on *nix systems. You will need to change the gpg_home as with the above example:

import gnupg

gpg_home = "~/.gnupg"
gpg = gnupg.GPG(gnupghome=gpg_home)

data = raw_input("Enter full path of file to encrypt: ")
rkeys = raw_input("Enter key IDs separated by spaces: ")
savefile = data+".asc"

afile = open(data, "rb")
encrypted_ascii_data = gpg.encrypt_file(afile, rkeys.split(), always_trust=True, output=savefile)
afile.close()

My work here is done! :)

BTW, both these examples use Python 2.7, for Python 3 you'll need to modify the raw_input() lines to use input() instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!