Skip to content

Instantly share code, notes, and snippets.

@ryantuck
Last active April 30, 2024 23:44
Show Gist options
  • Save ryantuck/56c5aaa8f9124422ac964629f4c8deb0 to your computer and use it in GitHub Desktop.
Save ryantuck/56c5aaa8f9124422ac964629f4c8deb0 to your computer and use it in GitHub Desktop.
working example of using gnupg in python
# 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='me@email.com',
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=['me@email.com'],
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)
@yzorg
Copy link

yzorg commented Sep 9, 2021

@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.

@abhishekkumaresan
Copy link

@ryantuck is it possible to decrypt a file with public-key with this library

@gcpdiscacciati
Copy link

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

@TrevorBenson
Copy link

TrevorBenson commented May 17, 2023

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>)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment