我知道可以使用 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/