我正在尝试使用经过加密签名的Django发送电子邮件。它应该是这样的:
我不知道如何获得签名值:
signature = str(gpg.sign(basetext, detach=True))
# Now signature is None.
完整代码:
body = """
This is the original message text.
:)
"""
basemsg = MIMEText(body)
gpg = gnupg.GPG()
basetext = basemsg.as_string().replace('\n', '\r\n')
signature = str(gpg.sign(basetext, detach=True))
if signature:
signmsg = messageFromSignature(signature)
msg = MIMEMultipart(_subtype="signed", micalg="pgp-sha1",
protocol="application/pgp-signature")
msg.attach(basemsg)
msg.attach(signmsg)
print(msg.as_string(unixfrom=True))
else:
print('Warning: failed to sign the message!')
答案 0 :(得分:0)
正如我的评论所述,gnupg库有两个版本:一个被废弃,一个被维护。使用正确的python-gnupg
时,将测试以下代码是否正常工作:
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.message import Message
import gnupg
import os
def messageFromSignature(signature):
message = Message()
message["Content-Type"] = 'application/pgp-signature; name="signature.asc"'
message["Content-Description"] = "OpenPGP digital signature"
message.set_payload(signature)
return message
def signed_mail():
body = """
This is the original message text.
:)
"""
basemsg = MIMEText(body)
gnupghome = os.path.join(os.getenv('HOME', '/homeless'), '.gnupg')
gpg = gnupg.GPG(gnupghome=gnupghome, use_agent=True)
basetext = basemsg.as_string().replace("\n", "\r\n")
signature = str(gpg.sign(basetext, detach=True))
if signature:
signmsg = messageFromSignature(signature)
msg = MIMEMultipart(
_subtype="signed", micalg="pgp-sha1", protocol="application/pgp-signature"
)
msg.attach(basemsg)
msg.attach(signmsg)
print(msg.as_string(unixfrom=True))
else:
print("Warning: failed to sign the message!")
if __name__ == "__main__":
signed_mail()
输出:
From nobody Fri Jul 24 19:41:07 2020
Content-Type: multipart/signed; micalg="pgp-sha1"; protocol="application/pgp-signature"; boundary="===============7347302325830204740=="
MIME-Version: 1.0
--===============7347302325830204740==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
This is the original message text.
:)
--===============7347302325830204740==
Content-Type: application/pgp-signature; name="signature.asc"
Content-Description: OpenPGP digital signature
-----BEGIN PGP SIGNATURE-----
iHUEABEIAB0WIQQ7CPtOD4MLM1EdL8f8hi+zE9fGuAUCXxsdMwAKCRD8hi+zE9fG
uN6xAP46c05XTvo4tccCmGRABqjYQRXHHBMuUXqDbv8pmru2igEAmxO53cJkSmEh
+tr+0uHOt2ERB/eiSc+8+2x+9s+6Dmk=
=HRAe
-----END PGP SIGNATURE-----
--===============7347302325830204740==--