我现在花了几个小时,我找不到我的错误。我想要一个简单的例程来创建一个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: <c@roessner.co>\r\n')
out.write("To: <test@example.com>\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: <c@roessner.co>
To: <test@example.com>
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的例子,它看起来都一样(对我来说)。我在这里缺少什么?
非常感谢您提前帮助: - )
答案 0 :(得分:0)
这已经晚了几年,但对于任何来自谷歌的人来说都是显着的,请试试这个:
p7 = smime.sign(buf, SMIME.PKCS7_DETACHED)
out = BIO.MemoryBuffer()
out.write('From: %s\n' % sender)
out.write('To: %s\n' % to)
out.write('Subject: %s\n' % subject)
buf = BIO.MemoryBuffer(msg_str)
smime.write(out, p7, buf)