isislovecruft / python-gnupg

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

How to Import Private Key w/ Passphrase #194

Closed joshuamcginnis closed 7 years ago

joshuamcginnis commented 7 years ago

I'm able to import a private key with passphrase like so:

echo my_passphrase | gpg2 --batch --import /path/to/private.key

gpg: key XXX: "MY KEY" not changed
gpg: key xxxx: secret key imported                                                                          
gpg: Total number processed: 1                                                                                                                                     
gpg:              unchanged: 1                                                                                                                                                   
gpg:       secret keys read: 1                                                                                          
gpg:   secret keys imported: 1 

But I am unable to import a private key with a symmetric passphrase using this lib:

import sys
import gnupg

gpg = gnupg.GPG(homedir='~/.gnupg')

private_key = '/path/to/private.key'

result = gpg.import_keys(private_key)
print(result.results)

#[{'status': 'No valid data found', 'fingerprint': None}]```

What is the correct way to import this private key?

joshuamcginnis commented 7 years ago

Fixed by reading the key contents and passing it to import_keys: result = gpg.import_keys(open(private_key, 'rb').read())

pajuscz commented 2 years ago

I am having the same issue. while looking into the code I don't thin it is possible to import a key using passpharse, because the passpharse is set to False by default.

The _handle_io: def _handle_io(self, args, file, result, passphrase=False, binary=False):

called from import_keys(self, key_data) is called in this fashion: self._handle_io(['--import'], data, result, binary=True) I don't see a way to pass passphase there.

When I 'hard-code' the passphasee into the self._handle_io(['--import'], data, result, passphrase='secret', binary=True) It works as expected. I think there should be a posibility to pass passpharse as an argument into GPG.import_keys()

erickeniuk commented 1 year ago

Using @pajuscz 's suggestion, I provided the solution for importing keys with passphrases on #284 .

Add passphrase=False to def import_keys(...) and then provide passphrase to self._handle_io(['--import'], data, result, passphrase, binary=True).

If you provide no passphrase to import_keys(), it should default to False which is already the default for _handle_io(...) under _utils.py, else you can provide the passphrase of the key.

I confirmed this was working, although I did need to make some squirrel patches to my _parsers.py for some unknown status errors.