Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@julian-klode
Created June 8, 2019 23:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julian-klode/b5d2c596ed780208ddd70215b01ae93c to your computer and use it in GitHub Desktop.
Save julian-klode/b5d2c596ed780208ddd70215b01ae93c to your computer and use it in GitHub Desktop.
#!/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