Created
June 8, 2019 23:08
-
-
Save julian-klode/b5d2c596ed780208ddd70215b01ae93c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""Encrypt/Decrypt GPG/MIME messages""" | |
import os | |
import sys | |
import email.mime.application | |
import email.mime.multipart | |
import email.mime.message | |
import errno | |
import mimetypes | |
import gnupg | |
from argparse import ArgumentParser | |
def encrypt(message, recepients): | |
encrypted_content = gnupg.GPG().encrypt(message.as_string(), recepients) | |
enc = email.mime.application.MIMEApplication( | |
_data=str(encrypted_content), | |
_subtype='octet-stream; name="encrypted.asc"', | |
_encoder=email.encoders.encode_7or8bit) | |
enc['Content-Description'] = 'OpenPGP encrypted message' | |
enc.set_charset('us-ascii') | |
control = email.mime.application.MIMEApplication( | |
_data='Version: 1\n', | |
_subtype='pgp-encrypted', | |
_encoder=email.encoders.encode_7or8bit) | |
control.set_charset('us-ascii') | |
encmsg = email.mime.multipart.MIMEMultipart( | |
'encrypted', | |
protocol='application/pgp-encrypted') | |
encmsg.attach(control) | |
encmsg.attach(enc) | |
encmsg['Content-Disposition'] = 'inline' | |
for key, value in message.items(): | |
if key not in ["Content-Disposition", "Content-Type"]: | |
encmsg[key] = value | |
return encmsg.as_string() | |
def decrypt(message): | |
return str(gnupg.GPG().decrypt(message.as_string())) | |
def main(): | |
parser = ArgumentParser(description="""\ | |
Unpack a MIME message into a directory of files. | |
""") | |
parser.add_argument('-d', '--decrypt', action="store_true") | |
parser.add_argument('recipient') | |
args = parser.parse_args() | |
msg = email.message_from_file(sys.stdin) | |
if args.decrypt: | |
sys.stdout.write(decrypt(msg)) | |
else: | |
sys.stdout.write(encrypt(msg, [args.recipient])) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment