isislovecruft / python-gnupg

A modified version of python-gnupg, including security patches, extensive documentation, and extra features.
Other
424 stars 172 forks source link

Question: Understanding recipients parameters for encrypting files #275

Open fluxquantum opened 4 years ago

fluxquantum commented 4 years ago

Hi, could someone either direct me to documentation or help me understand how to programmatically set the recipients parameter for the encryption method? And understand what value to use for the recipient? Our use case is that we are downloading a public key from s3, use it to decrypt a file, perform some processing, and then re-encrypting the file.

What's the best approach for setting the recipient? I have seen implementations where we can extract the keyid or fingerprint from the public key itself, or hardcoding an email. I don't understand what approach to use in the case where don't necessarily know how the public keys were created.

Thank you for your time.

kiorq commented 3 years ago

Sharing what worked for me after having to do something similar myself. It seems the recipients parameter is the fingerprints or the keyIDs of the recipient's public/private keys.

See documentation:

https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/gnupg.py#L987

So you have two options.

  1. Import an existing public/private key using the import_keys method and use the fingerprint from the imported key to pass into the encrypt method.
    
    with open(public_key_file, 'rb') as f:
    public_key = gpg.import_keys(f.read())
    fingerprint = public_key.fingerprints[0]

gpg.encrypt("My message", fingerprint)

2. Create a new key for the recipient programmatically using `gen_key_input` and `gen_key`.
```python
input_data = gpg.gen_key_input(
    key_type="RSA",
    key_length=4096,
    name_email="recipient@example.com",
    expire_date="2021-06-06",
    passphrase="shhh",
key = gpg.gen_key(input_data)
fingerprint = key.fingerprint

gpg.encrypt("My message", fingerprint)

Based on my understanding so far, I believe option 1 is the most appropriate approach when moving encrypted content.

You may have figured this out already, but this may help someone else with a similar issue like me last week. If you had any luck feel free to backup or correct anything I may have gotten wrong.