Fix encrypting to filenames and/or file-like objects.

* FIXES Issue#24, which prevented python-gnupg from encrypting to a
   filename given as a string to the `output` parameter of
   `gnupg.GPGMeta._encrypt()`.

 * THANKS TO by Bill Buddington of SecureDrop and Yan Zhu of the
   Electronic Frontier Foundation (EFF) for finding and reporting the
   bug. The ticket for this bug can be viewed at:
   https://github.com/isislovecruft/python-gnupg/issues/24
fix/24-output-to-filename
Isis Lovecruft 2014-08-02 01:56:20 +00:00
parent 5207ccc6b4
commit 137d3ac5c5
No known key found for this signature in database
GPG Key ID: 5C17776E27F7E84D
1 changed files with 24 additions and 10 deletions

View File

@ -766,10 +766,10 @@ class GPGBase(object):
**recipients** keys. If False, display trust
warnings. (default: True)
:param str output: The output file to write to. If not specified, the
encrypted output is returned, and thus should be
stored as an object in Python. For example:
:type output: str or file-like object
:param output: The output file to write to. If not specified, the
encrypted output is returned, and thus should be stored
as an object in Python. For example:
>>> import shutil
>>> import gnupg
@ -808,17 +808,23 @@ class GPGBase(object):
"""
args = []
## FIXME: GnuPG appears to ignore the --output directive when being
## programmatically driven. We'll handle the IO ourselves to fix this
## for now.
output_filename = None
if output:
if getattr(output, 'fileno', None) is not None:
## avoid overwrite confirmation message
if getattr(output, 'name', None) is None:
if os.path.exists(output):
os.remove(output)
args.append('--output %s' % output)
else:
if getattr(output, 'name', None) is not None:
output_filename = output.name
if os.path.exists(output.name):
os.remove(output.name)
args.append('--output %s' % output.name)
#args.append('--output %s' % output.name)
else:
output_filename = output
if os.path.exists(output):
os.remove(output)
#args.append('--output %s' % output)
if armor: args.append('--armor')
if always_trust: args.append('--always-trust')
@ -877,4 +883,12 @@ class GPGBase(object):
self._handle_io(args, data, result,
passphrase=passphrase, binary=True)
log.debug("\n%s" % result.data)
if output_filename:
log.info("Writing encrypted output to file: %s" % output_filename)
with open(output_filename, 'w+') as fh:
fh.write(result.data)
fh.flush()
log.info("Encrypted output written successfully.")
return result