cryptography
cryptography copied to clipboard
Documentation: Add an example how to sign/encrypt/sign and encrypt an email
9 andhttps://github.com/pyca/cryptography/issues/10664, both of which seem to have not really been resolved.
My assumption is: it is possible to sign/encrypt/sign and encrypt emails with cryptography, sources: https://m2crypto.readthedocs.io/en/latest/howto.migration.html#signing or https://cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/#cryptography.hazmat.primitives.serialization.pkcs7.PKCS7EnvelopeBuilder
Yet I'm struggling to properly send encrypted emails with cryptography and Python standard modules. The building blocks are there, I can encrypt and send emails, yet the result isn't production ready:
- they contain headers and the content-type information
- long lines are broken up into multiple lines
- no subject
Here's how my code currently looks like:
message["Subject"] = subject
message["To"] = recipient
message["From"] = from
message["Sender"] = sender
message.set_content(content)
if attachments:
for attachment in attachments:
message.add_attachment(
base64.b64decode(attachment.content),
maintype="application",
subtype="octet-stream",
filename=attachment.name,
)
options = [pkcs7.PKCS7Options.Text]
encrypted_content = (
pkcs7.PKCS7EnvelopeBuilder()
.set_data(message.as_bytes())
.add_recipient(certificate)
.encrypt(serialization.Encoding.SMIME, options)
)
encrypted_message = BytesParser().parsebytes(encrypted_content)
encrypted_message["Subject"] = subject
encrypted_message.set_payload(encrypted_content)
It would be great to have an authoritative example how to send encrypted emails with cryptography, there are a lot of outdated examples for deprecated packages on the internet each making the world a little less safe.
envelope is a Python package that implements email signing and encryption on top of cryptography, a link to that package may suffice.