我现在花了几个小时,但找不到我的错误。我想要一个简单的例程来创建 S/MIME 签名消息,稍后可以与 smtplib 一起使用。
这是我到目前为止所拥有的:
#!/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: <[email protected] /cdn-cgi/l/email-protection>\r\n')
out.write("To: <[email protected] /cdn-cgi/l/email-protection>\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
不幸的是,它只产生:
From: <[email protected] /cdn-cgi/l/email-protection>
To: <[email protected] /cdn-cgi/l/email-protection>
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
如果我添加代码来显示 p7,我可以看到它创建了一个数据 blob。
我使用原始证书和密钥。但我之前也用自签名证书测试过。总是相同的结果。
我检查了 M2Crypto 中的几乎所有示例,它看起来都一样(对我来说)。我在这里缺少什么?
非常感谢您提前提供帮助:-)