-
-
Save ryantuck/56c5aaa8f9124422ac964629f4c8deb0 to your computer and use it in GitHub Desktop.
# install: | |
# pip3 install python-gnupg | |
# note - gpg needs to be installed first: | |
# brew install gpg | |
# apt install gpg | |
# you may need to also: | |
# export GPG_TTY=$(tty) | |
import gnupg | |
gpg = gnupg.GPG() | |
# generate key | |
input_data = gpg.gen_key_input( | |
name_email='[email protected]', | |
passphrase='passphrase', | |
) | |
key = gpg.gen_key(input_data) | |
print(key) | |
# create ascii-readable versions of pub / private keys | |
ascii_armored_public_keys = gpg.export_keys(key.fingerprint) | |
ascii_armored_private_keys = gpg.export_keys( | |
keyids=key.fingerprint, | |
secret=True, | |
passphrase='passphrase', | |
) | |
# export | |
with open('mykeyfile.asc', 'w') as f: | |
f.write(ascii_armored_public_keys) | |
f.write(ascii_armored_private_keys) | |
# import | |
with open('mykeyfile.asc') as f: | |
key_data = f.read() | |
import_result = gpg.import_keys(key_data) | |
for k in import_result.results: | |
print(k) | |
# encrypt file | |
with open('plain.txt', 'rb') as f: | |
status = gpg.encrypt_file( | |
file=f, | |
recipients=['[email protected]'], | |
output='encrypted.txt.gpg', | |
) | |
print(status.ok) | |
print(status.status) | |
print(status.stderr) | |
print('~'*50) | |
# decrypt file | |
with open('encrypted.txt.gpg', 'rb') as f: | |
status = gpg.decrypt_file( | |
file=f, | |
passphrase='passphrase', | |
output='decrypted.txt', | |
) | |
print(status.ok) | |
print(status.status) | |
print(status.stderr) |
@coolteddy no clue, apologies :)
Hi I tested your code and it works as is, but I don't think it's doing what you expected.
After running the program once.
Run
gpg --delete-secret-keys [email protected]
gpg --delete-key [email protected]
that will delete the keys from your PC.
Then try running the code again, but comment out the bit that creates the key and just get the key from the file.
It doesn't work then, but it should.
@tsarpi That might be true for end user or "pet servers", but my job environments are all kubernetes, so I'll need this version of script that always imports b/c this job will be running on ephemeral storage, key and passphrase will come form k8s secret provider and injected into job.
I won't need lines 16:24, but I will need 39.
@ryantuck is it possible to decrypt a file with public-key with this library
Hi there, @ryantuck! Do you know if it is possible to sign a file with this library? Like the gpg --edit keyid > sign commands on the CLI
Hi there, @ryantuck! Do you know if it is possible to sign a file with this library? Like the gpg --edit keyid > sign commands on the CLI
@gcpdiscacciati
python-gnupg supports signing during encryption by adding the fingerprint to the sign
argument:
gpg.encrypt(data, sign=<fingerprint>)
Hi @ryantuck, do you remember which version of gnupg ? thanks for the gist