问题描述
我正在使用email.Message类和gnupg库来
I'm using email.Message class and gnupg library to:
1-解析从Twisted imap4客户端获取的电子邮件字符串。
1 - parse email string fetched from Twisted imap4 client.
2-获取附件,.pgp
2 - get the attached file, a .pgp
3-解密。
我可以解密典型的邮件内容,例如:
I can decrypt typical mail content, as:
-----BEGIN PGP MESSAGE-----
Version: PGP 9
(...)
-----END PGP MESSAGE-----
,但是依恋确实使我的生活变得地狱。
but the attachment affair is really making my life a hell.
我尝试了很多不同的方法,但是最合乎逻辑的应该是:
Well, I tried a lot of different ways, but the most logical should be this:
message = email.message_from_string(content)
if message.is_multipart():
attachment = message.get_payload(1)
gpg = gnupg.GPG(gnupghome=settings.PGP_PATH)
return gpg.decrypt_file(attachment.get_payload(), passphrase=settings.PGP_PASSPH)
附件var的第一行是:
The attachment var first lines are:
From nobody Mon Oct 15 18:54:12 2012
Content-type: application/octet-stream;
name="No_Norm_AMLT_908_1210201201.txt.pgp"
Content-Disposition: attachment; filename="No_Norm_AMLT_908_1210201201.txt.pgp"
Content-Transfer-Encoding: base64
然后是所有加密的东西。
And then all the encrypted stuff.
反正...真的很奇怪,有些东西我没得到。如果从普通的邮件客户端软件(例如Thunderbird)下载附件,则会得到一个看起来是二进制的.pgp文件(如果使用纯文本编辑器编辑该附件,则会出现奇怪的字符),并且可以使用bash命令对其进行解密:
Anyway... it's really strange, there's something I don't get. If I download the attachment from a normal mail client software (i.e. Thunderbird) I get a .pgp file that seems binary (strange characters appears if I edit it with a plain text editor) and I can decrypt it using the bash command:
gpg --decrypt No_Norm_AMLT_908_1210201201.txt.pgp
我不知道如何使用email.Message类和gnupg获得相同的结果(解密文件),我试图将附件的有效内容保存到文件中,这是与从Thunderbird下载的文件不同,我无法解密它,我还尝试将其放入StringIO,并使用base64对其进行编码。
I don't know how to get the same result (the file decrypted) using email.Message class and gnupg, I tried to save the payload of the attachment to a file, and this is different from the downloaded from Thunderbird one, I can't decrypt it, I tried also to put it into a StringIO, and also encoding it with base64.
我收到的消息从gpg获得的是:
The message I get from gpg is:
[GNUPG:] NODATA 1
[GNUPG:] NODATA 2
gpg: decrypt_message failed: eof
谢谢!
推荐答案
好了!我必须:
base64.decodestring(attachment.get_payload())
然后使用gpg对其解密,然后开始工作。可以通过以下标头找出原因:
then decrypt it using gpg, and worked. This can be figured out because of the header:
Content-Transfer-Encoding: base64
最终代码是:
message = email.message_from_string(content)
if message.is_multipart():
attachment = message.get_payload(1)
gpg = gnupg.GPG(gnupghome=settings.PGP_PATH)
return gpg.decrypt_file(base64.decodestring(attachment.get_payload()),
passphrase=settings.PGP_PASSPH)
这篇关于解密从电子邮件附加的gpg文件(file.pgp)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!