Python using M2Crypto signing a message with S/MIME
<p>I spent hours now and I can not find my error. I want a simple routine that creates a S/MIME signed message that could be used with smtplib later.</p>

<p>This is, what I have so far:</p>

<pre><code>#!/usr/bin/python2.7
# -*- coding: utf-8 -*-

from __future__ import print_function
from __future__ import absolute_import

import sys

from M2Crypto import BIO, Rand, SMIME

text = """Das ist ein einfacher Satz"""

sign_cert = "cert.pem"
sign_key = "key.pem"

# -----------------------------------------------------------------------------

class SignError(Exception):
    pass


def sign(msg):
    if "unsigned" not in msg:
        raise SignError()

    # Seed the PRNG.
    Rand.load_file('.rnd', -1)

    # Make a MemoryBuffer of the message.
    msg_bio = BIO.MemoryBuffer(msg["unsigned"])

    signer = SMIME.SMIME()

    # Load key and certificate
    try:
        signer.load_key(sign_key, sign_cert)
    except BIO.BIOError:
        raise SignError()

    p7 = signer.sign(msg_bio, flags=SMIME.PKCS7_TEXT)

    # Recreate buf.
    msg_bio = BIO.MemoryBuffer(msg["unsigned"])

    # Output p7 in mail-friendly format.
    out = BIO.MemoryBuffer()
    out.write('From: &lt;c@roessner.co&gt;\r\n')
    out.write("To: &lt;test@example.com&gt;\r\n")
    out.write("Subject: M2Crypto S/MIME testing\r\n")
    signer.write(out, p7, data_bio=msg_bio, flags=SMIME.PKCS7_TEXT)

    msg["signed"] = out.read()
    out.close()

    # Save the PRNG's state.
    Rand.save_file(".rnd")


if __name__ == "__main__":
    msg = dict(unsigned=text)

    try:
        sign(msg)
    except SignError:
        print("Unable to sign message", file=sys.stderr)

    if "signed" in msg:
        print(msg["signed"])

    sys.exit()

# vim: ts=4 sw=4 expandtab
</code></pre>

<p>Unfortunately, it only produces:</p>

<pre><code>From: &lt;c@roessner.co&gt;
To: &lt;test@example.com&gt;
Subject: M2Crypto S/MIME testing
MIME-Version: 1.0
Content-Type: multipart/signed; protocol="application/x-pkcs7-signature"; micalg="sha-256"; boundary="----B9B56E4AFF9BD5BC9B3B8FEDDE632A4C"

This is an S/MIME signed message

------B9B56E4AFF9BD5BC9B3B8FEDDE632A4C
Content-Type: text/plain

Das ist ein einfacher Satz
</code></pre>

<p>If I add code to display the p7, I can see that it has created a data blob.</p>

<p>I use an original certificate and key. But I also tested with a self signed certificate before. Always the same result.</p>

<p>I checked nearly all examples from M2Crypto and it looks the same (for me). What am I missing here?</p>

<p>Thanks a lot for helping in advance :-)</p>