python - 如何读取不受信任的证书以使用 Python 提取信息?

标签 python ssl certificate

我知道可以使用 OpenSSL 或 M2Crypto 在 Python 中读取证书,如 How can I retrieve the TLS/SSL peer certificate of a remote host using python? 中的详细解释,但我希望能够使用不受信任的证书执行相同的操作。

不可信是指我(例如)刚刚生成的证书并将 csr 输出粘贴到我的 python 函数中。

这是我生成 csr 的方式:

openssl req -new -newkey rsa:2048 -nodes -keyout domain.key -out domain.csr

并将 domain.csr 的输出用于 S.O. 中的代码。之前的问题。

如预期的那样,这是行不通的。为了更快,使用 Openssl 执行相同的操作会导致相同的错误:

openssl x509 -text -in Domain.csr -noout

unable to load certificate 139698977908608:error:0906D06C:PEM routines:PEM_read_bio:no start >line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

期望:可信证书是这里的关键问题。

我该怎么做?

感谢您的帮助!

更新: 通过搜索更多内容,我读到如果私钥位于来自此 S.O 答案 https://stackoverflow.com/a/12312994/330867 的证书(又名 pem)中,这将起作用。 ,但我要实现的是一个系统,该系统可以从来自其他人而不是我的证书中提取信息。而且我很确定“其他人”不想分享他们的私钥,所以我仍然被困住了。有什么想法吗?

更新 2: x509 和 req 证书之间似乎存在差异。如前所述,使用之前的命令生成的是请求。

现在我可以使用第一个 SO 链接读取 x509 证书,但是我如何在 python 中读取 req 证书?

最佳答案

好的,我找到了答案,我相信它会对其他人有所帮助!

因此,“req”证书和 x509 证书之间存在重要区别!

在x509中,私钥也包含在文件中!

因此,在下文中,我将展示如何使用 REQ 和 x509 类型的证书生成证书并在 Python 中读取它。

使用“req”证书:

生成它:

openssl req -new -newkey rsa:2048 -nodes -keyout domain.key -out domain.csr

阅读它:

import OpenSSL
# cert contains the content of domain.csr
OpenSSL.crypto.load_certificate_request(OpenSSL.crypto.FILETYPE_PEM, cert).get_subject().get_components()

使用“x509”证书:

生成它:

openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem

阅读它:

import OpenSSL
# cert contains the content of cert.pem
OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert).get_subject().get_components()

就是这样!

区别在于您如何在 OpenSSL.crypto 中加载证书:

  • 对于“请求”:load_certificate_request()
  • 对于“x509”:load_certificate()

就这么简单;)

关于python - 如何读取不受信任的证书以使用 Python 提取信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22429770/

相关文章:

apache - 我应该获得没有 ssl 还是开放 ssl 的 Apache?谁能告诉我 ssl 到底是什么?

node.js - WSS - 连接建立时出错:net::ERR_CONNECTION_CLOSED

redirect - 每个子域和根重定向一个 SSL 证书

ios - Apple Pay 是否可以使用他人的应用商户 ID?

Python 3 - 如何连续删除句子中的字母?

scala - 如何使用 scala 代码在 Play framework 2.3.x 中启用 HSTS?

python - 如何停止将 SIGINT 传递给 python 中的子进程?

javascript - 从(邪恶的)feedly 导出 "saved for later"

python - 广度优先搜索 - 标准 Python 库

python - ValueError : Sample is not large enough to include at least one row of data. 请增加 `sample` 中的字节数