【问题标题】:Python3 - imaplib - decrypt using pem certificatePython3 - imaplib - 使用 pem 证书解密
【发布时间】:2020-11-26 15:52:09
【问题描述】:

作为更大工作流程的一部分,我获得了电子邮件和密码,以及该证书的 .pfx 证书和密码。我需要使用它们来下载特定的电子邮件(特别是其附件),以便可以在其他脚本中进行处理。

我已经设法将 .pfx 文件转换为 .pem 文件。使用下面的代码,我可以下载消息:

import email
import imaplib

EMAIL = 'test@test.com'
PASSWORD = 'testpassword'
SERVER = "outlook.office365.com"

# Connect to the server and go to its inbox
mail = imaplib.IMAP4_SSL(SERVER, port=993)
mail.login(EMAIL, PASSWORD)
mail.select('inbox')

# Get the relevant mail ID
status, ids = mail.search(None, '(HEADER Subject "Testmessage_")')
mail_id = ids[0].split()[0]

# Fetch the mail, get the data, write the file
status, contents = mail.fetch(mail_id, '(RFC822)')
data = contents[0][1]
with open("outputfile.txt", "wb") as outputfile:
    outputfile.write(data)

然后我可以使用以下命令使用 OpenSSL 解码 outputfile.txt:

openssl cms -decrypt -in outputfile.txt -inkey cert.pem > outputmessage.txt

我可以确认在 outputmessage.txt 文件中,附件的内容是可见的,并且通过一些解决方法,可以在我的 Python 脚本的其余部分中使用。

但是,这意味着使用多个临时文件和(至少)三个不同的命令(再次是 python - openssl - python)。我想在 Python 中完成所有这些操作,因此我不必创建临时文件,并且可以立即在以下脚本中处理结果。 此外,我更愿意使用尽可能少的外部依赖项。

我已经看到提到 M2Crypto 和密码学,但我似乎无法让任何一个包在我的机器上工作(有轮子的东西?)。还有其他选择吗?

【问题讨论】:

    标签: python python-3.x pem imaplib


    【解决方案1】:

    琐碎,

    import subprocess
    
    # ...
    
    subprocess.run(['openssl', 'cms', '-decrypt',
            '-inkey', 'cert.pem', '-out', 'outputmessage.txt'],
        input=data, check=True)
    

    我在本地没有openssl cms,但我从手册页猜测,如果您不传入-in 选项,它将读取标准输入。如果不是这样,可以试试-in- 之类的方法,或者将- 替换为/dev/stdin 或您的平台提供的任何内容。

    【讨论】:

      猜你喜欢
      • 2011-08-08
      • 2017-02-08
      • 2011-08-15
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 2012-02-08
      相关资源
      最近更新 更多