This change has no functional change, it just makes it clear that there is a distinct condition for even trying to decrypt.
It paves the way for adding in a decryption mechanism that tries to use GnuPG. Signed-off-by: Daniel Kahn Gillmor <d...@fifthhorseman.net> --- email-print-mime-structure | 48 +++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/email-print-mime-structure b/email-print-mime-structure index 644efb1..6507436 100755 --- a/email-print-mime-structure +++ b/email-print-mime-structure @@ -70,33 +70,39 @@ class MimePrinter(object): nbytes = len(payload) print(f'{prefix}{z.get_content_type()}{cset}{disposition}{fname} {nbytes:d} bytes') + try_decrypt:bool = True if self.args.pgpkey else False - if self.args.pgpkey and \ + if try_decrypt and \ (parent is not None) and \ (parent.get_content_type().lower() == 'multipart/encrypted') and \ (str(parent.get_param('protocol')).lower() == 'application/pgp-encrypted') and \ (num == 2): - if pgpy is None: - logging.warning(f'Python module pgpy is not available, not decrypting (try "apt install python3-pgpy")') - else: - cryptopayload:Optional[Message] = None - keyname:str - for keyname in self.args.pgpkey: - try: - key:pgpy.PGPKey - key, _ = pgpy.PGPKey.from_file(keyname) - msg:pgpy.PGPMessage = pgpy.PGPMessage.from_blob(z.get_payload()) - msg = key.decrypt(msg) - cryptopayload = email.message_from_bytes(msg.message) - break - except: - pass - if cryptopayload is None: - logging.warning(f'Unable to decrypt') + cryptopayload:Optional[Message] = None + ciphertext:Union[List[Message],str,bytes,None] = z.get_payload() + if not isinstance(ciphertext, str): + logging.warning('encrypted part was not a leaf mime part somehow') + return + if self.args.pgpkey: + if pgpy is None: + logging.warning(f'Python module pgpy is not available, not attempting to decrypt with --pgpkey arguments {self.args.pgpkey} (try "apt install python3-pgpy")') else: - newprefix = prefix[:-3] + ' ' - print(f'{newprefix}↧ (decrypts to)') - self.print_tree(cryptopayload, newprefix + '└', z, 0) + keyname:str + for keyname in self.args.pgpkey: + try: + key:pgpy.PGPKey + key, _ = pgpy.PGPKey.from_file(keyname) + msg:pgpy.PGPMessage = pgpy.PGPMessage.from_blob(ciphertext) + msg = key.decrypt(msg) + cryptopayload = email.message_from_bytes(msg.message) + break + except: + pass + if cryptopayload is None: + logging.warning(f'Unable to decrypt') + else: + newprefix = prefix[:-3] + ' ' + print(f'{newprefix}↧ (decrypts to)') + self.print_tree(cryptopayload, newprefix + '└', z, 0) def print_tree(self, z:Message, prefix:str, parent:Optional[Message], num:int) -> None: if (z.is_multipart()): -- 2.24.0.rc1